开发者

Convert string to datetime in C#.net

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


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;
    }


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


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


DateTime.Parse(@"14/04/2010 10:14:49.PM");

that should work, not near VS at the moment so i cannot try it


Use convert function

using System;
using System.IO;

namespace stackOverflow
{
    class MainClass
    {
        public static void Main (string[] args)
        {

            Console.WriteLine(Convert.ToDateTime("14/04/2010 10:14:49.PM"));
            Console.Read();

        }
    }
}


I recommend using DateTime.ParseExact as the Parse method behaves slightly differently according to the current thread locale settings.

DateTime.ParseExact(yourString,
    "dd/MM/yyyy hh:mm:ss.tt", null)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜