Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to datetime in C#.net

Tags:

c#

datetime

Can someone help me convert the string 14/04/2010 10:14:49.PM to datetime in C#.net without losing the time format?

like image 951
dotnetrocks Avatar asked Dec 05 '10 20:12

dotnetrocks


Video Answer


3 Answers

var date = DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss.tt", null);

For string representation use

date.ToString(@"dd/MM/yyyy hh:mm:ss.tt");

Also you can create extention method like this:

    public enum MyDateFormats
    {
        FirstFormat, 
        SecondFormat
    }

    public static string GetFormattedDate(this DateTime date, MyDateFormats format)
    {
       string result = String.Empty;
       switch(format)  
       {
          case MyDateFormats.FirstFormat:
             result = date.ToString("dd/MM/yyyy hh:mm:ss.tt");
           break;
         case MyDateFormats.SecondFormat:
             result = date.ToString("dd/MM/yyyy");
            break;
       }

       return result;
    }
like image 163
Andrew Orsich Avatar answered Oct 07 '22 13:10

Andrew Orsich


DateTime result =DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy HH:mm:ss.tt",null);

You can now see the PM or AM and null value for format provider

like image 38
alnaji Avatar answered Oct 07 '22 13:10

alnaji


DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss");
like image 37
Raj Avatar answered Oct 07 '22 12:10

Raj