Example 1: c# get time
var timeString = DateTime.Now.ToString("hh:mm:ss");
var time24 = DateTime.Now.ToString("HH:mm:ss");
var timeString = DateTime.Now.ToString("t");
var shortTimeStr = DateTime.Now.ToShortTimeString();
var longTimeStr = DateTime.Now.ToLongTimeString();
var longtimestr = DateTime.Now.ToString("T");
var timeSpan = DateTime.Now.TimeOfDay;
Example 2: c# date
using System;
class Test {
static void Main() {
Console.WriteLine (DateTime.Now.ToString());
DateTime dt = new DateTime(2018, 7, 24);
Console.WriteLine (dt.ToString());
}
}
Example 3: c# datetime
var year = 2020;
var month = 12;
var day = 3;
var date = new DateTime(year, month, day);
var today = DateTime.Today;
var now = DateTime.Now;
Console.WriteLine(now.Hour);
Console.WriteLine(now.Minute);
var now = DateTime.Now;
var tomorrow = now.AddDay(1);
var monthBefore = now.AddMonths(-1);
var now = DateTime.Now;
string longDate = now.ToLongDateString();
string shortDate = now.ToShortDateString();
string normalDate = now.ToString("yyyy-MM-dd HH:mm");
DateTime myDate = DateTime.Parse("2012-07-12");
DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",null);
var hours = 2;
var minutes = 1;
var seconds = 7;
var timeSpan = new TimeSpan(hours, minutes, seconds);
var hourSpan = TimeSpan.FromHours(2);
var secondSpan = TimeSpan.FromSeconds(34);
var start = DateTime.Now;
var end = DateTime.Now.AddMinutes(90);
var duration = end - start;
var duration = new TimeSpan(3, 6, 9);
var newDuration = duration.Add(TimeSpan.FromSeconds(26))
var newDuration = duration.Subtract(TimeSpan.FromSeconds(12))
var timeSpan = new TimeSpan(2, 1, 0);
var totalMinutes = timeSpan.TotalMinutes;
var duration = TimeSpan.Parse("04:07:12");
var duration = TimeSpan.ParseExact("23:59", @"hh\:mm", null)
Example 4: c# datetime
var dat1 = new DateTime();
Console.WriteLine(dat1.ToString(System.Globalization.CultureInfo.InvariantCulture));
Console.WriteLine(dat1.Equals(DateTime.MinValue));
Example 5: C# time
DateTime dt1 = new DateTime();
DateTime dt2 = new DateTime(2015, 12, 31);
DateTime dt3 = new DateTime(2015, 12, 31, 5, 10, 20);
DateTime dt4 = new DateTime(2015, 12, 31, 5, 10, 20, DateTimeKind.Utc);