【问题标题】:c#.net String To Date Timec#.net 字符串到日期时间
【发布时间】:2018-10-30 07:19:53
【问题描述】:

假设我有一个字符串 date = "30-10-2018 15:00:00" 如何根据电脑区域和时间设置将其保存为日期时间变量

这是我目前得到的:

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

【问题讨论】:

标签: c# cultureinfo culture


【解决方案1】:

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

类似的东西。

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

【讨论】:

    【解决方案2】:

    使用 DateTime.Parse()

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

    【讨论】:

    • 很高兴我能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    相关资源
    最近更新 更多