-2

suppose i have a string date = "30-10-2018 15:00:00" how can i save it a datetime variable depending on pc region and time settings

This is what I got so far:

 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());
   }
RUL
  • 268
  • 2
  • 12
sushil.agarwal
  • 151
  • 1
  • 9
  • 2
    hard to believe this is over 8 years old but still relevant: https://msdn.microsoft.com/en-us/library/ms973825.aspx – jazb Oct 30 '18 at 07:26

2 Answers2

3

I have had issues string dates and converting them. Explicitly stating the date formats to check against helped.

something like this.

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

and then when it comes to the converting of the string date.

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;
        }
    }
Arianule
  • 8,811
  • 45
  • 116
  • 174
0

Use DateTime.Parse()

DateTime.Parse("30-10-2018 15:00:00")
Ivan Stefner
  • 32
  • 1
  • 6