将自定义日期转换为 mysql 日期时间

Convert custom date to mysql datetime

我有一个自定义日期格式,我想将其转换为 Datetime 这样我就可以插入到我的数据库中,我尝试使用 Datetime.ParseExact() 但我认为我误解了一些代码抛出 System.FormatException.

我有以下来自 csv 的日期格式

> 6/11/2014 9:00

我希望将其转换为 mysql datetime 格式

> 0000-00-00 00:00:00 OR yyyy-MM-dd HH:mm:ss

请注意,他们没有在原始日期中包含秒数,所以我不确定(没有将它们附加到末尾)如何将所有记录设置为只有“00”秒数,因为它不是可用。

我尝试了以下抛出异常的方法

DateTime myDate = DateTime.ParseExact("6/11/2014 9:00", "yyyy-MM-dd HH:mm",
                                   System.Globalization.CultureInfo.InvariantCulture);

首先需要将字符串转换为日期时间,然后将日期时间转换为字符串

string strd = "6/11/2014 9:00";
DateTime dt ;
//convert datetime string to datetime
if(DateTime.TryParse(strd, out dt))
{
  //convert datetime to custom datetime format 
  Console.WriteLine("The current date and time: {0: yyyy-MM-dd HH:mm:ss}", 
                   dt); ;
}

输出

如果您知道日期的格式,那么您可以这样做:

string stringDate = "6/11/2014 9:00";
//Your date formats of input
string[] dateFormats = new string[] 
{ 
    "d/MM/yyyy H:mm", 
    "dd/MM/yyyy H:mm", 
    "dd/MM/yyyy HH:mm", 
    "dd/MM/yyyy H:mm:ss", 
    "dd/MM/yyyy HH:mm:ss" 
    /* And other formats */ 
};

DateTime convertedDate;
bool isSuccessful = DateTime.TryParseExact(stringDate, dateFormats,
    System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out convertedDate);

if (isSuccessful)
{
    //If conversion was successful then you can print your date at any format you like
    //because you have your date as DateTime object
    Console.WriteLine(convertedDate.ToString("dd-MM-yyyy HH:mm:ss")); /* Or other format you want to print */
}

希望对你有所帮助

我知道回答这个问题已经晚了,但我 真的 感到惊讶 none 考虑直接使用 IFormatProvider to prevent a possible parsing error because of / format specifier or considering your string is a standard date and time format for your CurrentCulture or not so you can or can't use DateTime.TryParse(string, out DateTime) overload 的答案。

首先让我们看看DateTime.ParseExact documentation是怎么说的:

Converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly or an exception is thrown.

在您的情况下,它们不匹配。在这种情况下,您应该使用 d/MM/yyyy H:mm 格式来解析具有 / 作为 DateSeparator. I almost always suggest to use DateTime.TryParseExact method 的区域性的示例字符串;

string s = "6/11/2014 9:00";
DateTime dt;
if(DateTime.TryParseExact(s, "d/MM/yyyy H:mm", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"));
    // result will be 2014-11-06 09:00:00
}