在C#.net中将字符串转换为日期时间

5

有人能帮我将字符串 14/04/2010 10:14:49.PM 转换为 C#.net 中的日期时间格式,而不会丢失时间格式吗?


1
你说“不丢失时间格式”是什么意思? - Mark Byers
6个回答

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

使用字符串表示法

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

您可以像这样创建扩展方法:

也可以像这样创建扩展方法:

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

1
字符串表示应该使用hh而不是HH。在解析过程中,差异并不大,但对于输出,您将获得23h而不是11h(下午)。 - jdehaan
扩展方法也需要是静态的。 - Tim Jarvis
哦,是的。只是因为我附近没有VS。已更新。 - Andrew Orsich

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

现在您可以看到格式提供程序的上午/下午或空值。

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

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

应该可以,但我现在离开VS比较远,无法尝试。


这个程序有一个日期/月份格式不明确的问题,因此在某些情况下无法正常工作。 - Myster
我同意Myster的观点。行为取决于区域设置。 - jdehaan
假设这是DateTimeFormatInfo.CurrentInfo的正确格式,那么这应该可以工作。 - MerickOWA

0

使用转换函数

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();

        }
    }
}

0
我建议使用DateTime.ParseExact,因为根据当前线程的区域设置,Parse方法的行为会有些不同。
DateTime.ParseExact(yourString,
    "dd/MM/yyyy hh:mm:ss.tt", null)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接