Author : MD TAREQ HASSAN | Updated : 2021/03/22

DateTime in CSharp

Conversion to string

String to DateTime

var dt = Convert.ToDateTime("2020/04/27") 

var dt = (DateTime)Convert.ChangeType("2020/12/31", typeof(DateTime))


// DateTime.Parse Syntax
DateTime.Parse(String value)
DateTime.Parse(String value, IFormatProvider provider)
DateTime.Parse(String value, IFormatProvider provider, DateTypeStyles styles)

// DateTime.Parse Example 
string value = "1 January 2019";
CultureInfo provider = new CultureInfo("en-GB");
DateTime.Parse(value, provider, DateTimeStyles.NoCurrentDateDefault););

// DateTime.ParseExact
DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
                                       System.Globalization.CultureInfo.InvariantCulture);

DateTime Format

Convert to specific timezone

public const string TokyoTimeZoneId = "Tokyo Standard Time";
		
var ModifiedOn = TimeZoneInfo.ConvertTimeFromUtc(dateTime: DateTime.UtcNow,
                                                                destinationTimeZone: TimeZoneInfo.FindSystemTimeZoneById(TokyoTimeZoneId));