Datetime set time c# code example

Example 1: c# get time

//Return the time from DateTime object in string format
var timeString = DateTime.Now.ToString("hh:mm:ss");

//Return time in 24h format
var time24 = DateTime.Now.ToString("HH:mm:ss");
  
//Use short time format to return string value
var timeString = DateTime.Now.ToString("t");
var shortTimeStr = DateTime.Now.ToShortTimeString();

//Use long time format
var longTimeStr = DateTime.Now.ToLongTimeString();
var longtimestr = DateTime.Now.ToString("T");

//Return a TimeSpan from midnight
var timeSpan = DateTime.Now.TimeOfDay;

Example 2: c# set datetime

var date1 = new DateTime(2008, 5, 1, 8, 30, 52);
Console.WriteLine(date1);

Example 3: C# date type no time

/*
There is no dedicate pure Date class because you already have DateTime which can handle it. 

If you want the standard approach look at the DateTime.Date property which gives just the date 
portion of a DateTime with the time value set to 12:00:00 midnight (00:00:00).

E.g. Console.WriteLine($"Date only: {myDateVar.Date}");
*/