c#.net字符串到日期时间

时间:2018-10-30 07:19:54

标签: c# cultureinfo culture

假设我有一个字符串date =“ 30-10-2018 15:00:00” 如何根据PC区域和时间设置将其保存为datetime变量

这是我到目前为止得到的:

 DateTime evtd;
 try
   {
     switch (cmbDateType.SelectedIndex)
     {
       case 1:
       //India 
       string dateString = dr.Cells[10].Value.ToString(),
       fmt = "dd-MM-yyyy HH:mm:ss";// "g";
       CultureInfo provider = CultureInfo.InvariantCulture;
       //provider=new CultureInfo("en-IN");
       //CultureInfo In = new CultureInfo("en-IN");
       //"dd-MM-yyyy HH:mm:ss"
       //string fmt = In.DateTimeFormat.FullDateTimePattern;
       evtd = DateTime.ParseExact(dateString, fmt, provider);
       dtBillsEBN.Rows[i]["evtd"] = evtd; //Valid Till Date
       break;

       case 2: 
       //usa:"M/d/yyyy h:mm:ss tt"
       evtd = DateTime.ParseExact(dr.Cells[10].Value.ToString(), "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
       dtBillsEBN.Rows[i]["evtd"] = evtd; //Valid Till Date
       break;

       default:
       dtBillsEBN.Rows[i]["evtd"] = DBNull.Value;
       break;
     }
   }
   catch (Exception ex)
   {
     string msg = "Try Formating Valid Till Datein correct Format \nor\nchoose skip valid date update ";
     MessageBox.Show(ex.ToString());
   }

2 个答案:

答案 0 :(得分:3)

我遇到了字符串日期转换问题。明确说明要检查的日期格式。

类似这样的东西。

public static string[] DateTimeFormats => new string[]
    {
        "dd-MM-yyyy",
        "MM/dd/yyyy",
        "MM-dd-yyyy",
        "d-MM-yyyy",
        "d-M-yyyy",
        "dd-M-yyyy",
        "dd/MM/yyyy",            
        "yyyy/MM/dd HH:mm",
        "dd-MM-yyyy hh:mm",
         "dd-MM-yyyy HH:mm",
         "MMMM yyyy"
    };

,然后涉及字符串日期的转换。

internal static DateTime ChangeDateFormat(string dateAdded)
    {

        return ParseDateTime(DateTime.Now.ToString("dd-MM-yyyy hh:mm"), DateTimeFormats);
    }

 public static DateTime ParseDateTime(string dateTimeString, string[] formats)
    {
        try
        {
            DateTime dateStamp = DateTime.ParseExact(dateTimeString,
                formats, CultureInfo.CurrentCulture, DateTimeStyles.None);
            return dateStamp;
        }
        catch (Exception exe)
        {
            var message = $"dateTimeString: '{dateTimeString}', '{string.Join(",", formats)}'.";
            Utility.log(message);
            throw;
        }
    }

答案 1 :(得分:0)

使用DateTime.Parse()

DateTime.Parse("30-10-2018 15:00:00")