C# 将字符串转换为日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/919244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:12:17  来源:igfitidea点击:

Converting a String to DateTime

c#datetime

提问by

How do you convert a string such as 2009-05-08 14:40:52,531into a DateTime?

您如何将字符串转换2009-05-08 14:40:52,531为 a DateTime

回答by gehsekky

try this

尝试这个

DateTime myDate = DateTime.Parse(dateString);

a better way would be this:

更好的方法是这样的:

DateTime myDate;
if (!DateTime.TryParse(dateString, out myDate))
{
    // handle parse failure
}

回答by Sander

You have basically two options for this. DateTime.Parse()and DateTime.ParseExact().

为此,您基本上有两种选择。DateTime.Parse()DateTime.ParseExact()

The first is very forgiving in terms of syntax and will parse dates in many different formats. It is good for user input which may come in different formats.

第一个在语法方面非常宽容,可以解析许多不同格式的日期。它适用于可能采用不同格式的用户输入。

ParseExact will allow you to specify the exact format of your date string to use for parsing. It is good to use this if your string is always in the same format. This way, you can easily detect any deviations from the expected data.

ParseExact 将允许您指定用于解析的日期字符串的确切格式。如果您的字符串始终采用相同的格式,最好使用它。这样,您可以轻松检测与预期数据的任何偏差。

You can parse user input like this:

您可以像这样解析用户输入:

DateTime enteredDate = DateTime.Parse(enteredString);

If you have a specific format for the string, you should use the other method:

如果您有特定的字符串格式,则应使用其他方法:

DateTime loadedDate = DateTime.ParseExact(loadedString, "d", null);

"d"stands for the short date pattern (see MSDN for more info) and nullspecifies that the current culture should be used for parsing the string.

"d"代表短日期模式(有关更多信息,请参阅MSDN)并null指定应使用当前区域性来解析字符串。

回答by CMS

Since you are handling 24-hour based time and you have a comma separating the seconds fraction, I recommend that you specify a custom format:

由于您正在处理基于 24 小时的时间并且您有一个逗号分隔秒部分,我建议您指定自定义格式:

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

回答by Umair Baig

string input;
DateTime db;
Console.WriteLine("Enter Date in this Format(YYYY-MM-DD): ");
input = Console.ReadLine();
db = Convert.ToDateTime(input);

//////// this methods convert string value to datetime
///////// in order to print date

Console.WriteLine("{0}-{1}-{2}",db.Year,db.Month,db.Day);

回答by Krishna

Try the below, where strDate is your date in 'MM/dd/yyyy' format

尝试以下操作,其中 strDate 是您的“MM/dd/yyyy”格式的日期

var date = DateTime.Parse(strDate,new CultureInfo("en-US", true))

回答by dev.bv

You could also use DateTime.TryParseExact() as below if you are unsure of the input value.

如果您不确定输入值,您也可以使用 DateTime.TryParseExact() 如下。

DateTime outputDateTimeValue;
if (DateTime.TryParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out outputDateTimeValue))
{
    return outputDateTimeValue;
}
else
{
    // Handle the fact that parse did not succeed
}

回答by guneysus

Nobody seems to implemented an extension method. With the help of @CMS's answer:

似乎没有人实现扩展方法。在@CMS 的回答的帮助下:

Working and improved full source example is here: Gist Link

工作和改进的完整源代码示例在这里:Gist Link

namespace ExtensionMethods {
    using System;
    using System.Globalization;

    public static class DateTimeExtensions {
        public static DateTime ToDateTime(this string s, 
                  string format = "ddMMyyyy", string cultureString = "tr-TR") {
            try {
                var r = DateTime.ParseExact(
                    s: s,
                    format: format,
                    provider: CultureInfo.GetCultureInfo(cultureString));
                return r;
            } catch (FormatException) {
                throw;
            } catch (CultureNotFoundException) {
                throw; // Given Culture is not supported culture
            }
        }

        public static DateTime ToDateTime(this string s, 
                    string format, CultureInfo culture) {
            try {
                var r = DateTime.ParseExact(s: s, format: format, 
                                        provider: culture);
                return r;
            } catch (FormatException) {
                throw;
            } catch (CultureNotFoundException) {
                throw; // Given Culture is not supported culture
            }

        }

    }
}

namespace SO {
    using ExtensionMethods;
    using System;
    using System.Globalization;

    class Program {
        static void Main(string[] args) {
            var mydate = "29021996";
            var date = mydate.ToDateTime(format: "ddMMyyyy"); // {29.02.1996 00:00:00}

            mydate = "2016 3";
            date = mydate.ToDateTime("yyyy M"); // {01.03.2016 00:00:00}

            mydate = "2016 12";
            date = mydate.ToDateTime("yyyy d"); // {12.01.2016 00:00:00}

            mydate = "2016/31/05 13:33";
            date = mydate.ToDateTime("yyyy/d/M HH:mm"); // {31.05.2016 13:33:00}

            mydate = "2016/31 Ocak";
            date = mydate.ToDateTime("yyyy/d MMMM"); // {31.01.2016 00:00:00}

            mydate = "2016/31 January";
            date = mydate.ToDateTime("yyyy/d MMMM", cultureString: "en-US"); 
            // {31.01.2016 00:00:00}

            mydate = "11/?????/1437";
            date = mydate.ToDateTime(
                culture: CultureInfo.GetCultureInfo("ar-SA"),
                format: "dd/MMMM/yyyy"); 
         // Weird :) I supposed dd/yyyy/MMMM but that did not work !?$^&*

            System.Diagnostics.Debug.Assert(
               date.Equals(new DateTime(year: 2016, month: 5, day: 18)));
        }
    }
}

回答by Amir Twito

Use DateTime.Parse(string):

使用DateTime.Parse(string)

DateTime dateTime = DateTime.Parse(dateTimeStr);

回答by M.R.T2017

Put this code in a static class> public static class ClassName{ }

将此代码放在静态类中> public static class ClassName{ }

public static DateTime ToDateTime(this string datetime, char dateSpliter = '-', char timeSpliter = ':', char millisecondSpliter = ',')
{
   try
   {
      datetime = datetime.Trim();
      datetime = datetime.Replace("  ", " ");
      string[] body = datetime.Split(' ');
      string[] date = body[0].Split(dateSpliter);
      int year = date[0].ToInt();
      int month = date[1].ToInt();
      int day = date[2].ToInt();
      int hour = 0, minute = 0, second = 0, millisecond = 0;
      if (body.Length == 2)
      {
         string[] tpart = body[1].Split(millisecondSpliter);
         string[] time = tpart[0].Split(timeSpliter);
         hour = time[0].ToInt();
         minute = time[1].ToInt();
         if (time.Length == 3) second = time[2].ToInt();
         if (tpart.Length == 2) millisecond = tpart[1].ToInt();
      }
      return new DateTime(year, month, day, hour, minute, second, millisecond);
   }
   catch
   {
      return new DateTime();
   }
}

In this way, you can use

这样,您可以使用

string datetime = "2009-05-08 14:40:52,531";
DateTime dt0 = datetime.TToDateTime();

DateTime dt1 = "2009-05-08 14:40:52,531".ToDateTime();
DateTime dt5 = "2009-05-08".ToDateTime();
DateTime dt2 = "2009/05/08 14:40:52".ToDateTime('/');
DateTime dt3 = "2009/05/08 14.40".ToDateTime('/', '.');
DateTime dt4 = "2009-05-08 14:40-531".ToDateTime('-', ':', '-');