Create Dates and Times from Strings - CSharp Language Basics

CSharp examples for Language Basics:Date Time

Description

Create Dates and Times from Strings

Demo Code

using System;//  w w  w. j a va 2 s  .  c o  m
class MainClass
{
   public static void Main(string[] args)
   {
      string ds1 = "Sep 2020";
      string ds2 = "Monday 5 September 2020 14:15:33";
      string ds3 = "5,9,5";
      string ds4 = "5/9/2020 14:15:33";
      string ds5 = "2:15 PM";
      DateTime dt1 = DateTime.Parse(ds1);
      DateTime dt2 = DateTime.Parse(ds2);
      DateTime dt3 = DateTime.Parse(ds3);
      DateTime dt4 = DateTime.Parse(ds4);
      DateTime dt5 = DateTime.Parse(ds5);
      Console.WriteLine("String: {0} DateTime: {1}", ds1, dt1);
      Console.WriteLine("String: {0} DateTime: {1}", ds2, dt2);
      Console.WriteLine("String: {0} DateTime: {1}", ds3, dt3);
      Console.WriteLine("String: {0} DateTime: {1}", ds4, dt4);
      Console.WriteLine("String: {0} DateTime: {1}", ds5, dt5);
      DateTime dt6 = DateTime.ParseExact("2:13:30 PM", "h:mm:ss tt", null);
      DateTime dt7 = DateTime.ParseExact("Mon, 05 Sep 2020 14:13:30 GMT", "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", null);
      DateTime dt8 = DateTime.ParseExact("September 05", "MMMM dd", null);
      Console.WriteLine(dt6);
      Console.WriteLine(dt7);
      Console.WriteLine(dt8);
   }
}

Result


Related Tutorials