Converting a String to DateTimeConverting dd/mm/yyyy formatted string to Datetimehow do i convert string to datetime in c#String yy-MM-dd HH:mm:ss.SSS convert to datetime in C#Converting a string into date format in the code behindConvert dd/MM/yyyy hh:mm tt string date to C# dateMost efficient way to convert this string to DateTimehow to convert string to datetime in c#.netConvert string “2017-01-01T12:00:33:123456Z+02” to DateTimeConvert String To DateTime (d MM yyyy)Convert APRIL, 03/2013 string to DateTime in C#What is the difference between String and string in C#?How do I enumerate an enum in C#?How do you set a default value for a MySQL Datetime column?How do you get a timestamp in JavaScript?How do you convert a byte array to a hexadecimal string, and vice versa?Should I use the datetime or timestamp data type in MySQL?Case insensitive 'Contains(string)'Converting string into datetimeHow do I get a consistent byte representation of strings in C# without manually specifying an encoding?C# DateTime to “YYYYMMDDHHMMSS” format

Identifying "long and narrow" polygons in with PostGIS

Given this phrasing in the lease, when should I pay my rent?

Does Doodling or Improvising on the Piano Have Any Benefits?

Telemetry for feature health

Ways of geometrical multiplication

Personal or impersonal in a technical resume

I'm just a whisper. Who am I?

How to make money from a browser who sees 5 seconds into the future of any web page?

How to test the sharpness of a knife?

If Captain Marvel (MCU) were to have a child with a human male, would the child be human or Kree?

How can I, as DM, avoid the Conga Line of Death occurring when implementing some form of flanking rule?

Alignment of six matrices

Deciphering cause of death?

How many people need to be born every 8 years to sustain population?

Would a primitive species be able to learn English from reading books alone?

How do you justify more code being written by following clean code practices?

Why is the sun approximated as a black body at ~ 5800 K?

Why do Radio Buttons not fill the entire outer circle?

Overlapping circles covering polygon

Should I assume I have passed probation?

Origin of pigs as a species

Why does a 97 / 92 key piano exist by Bösendorfer?

Giving feedback to someone without sounding prejudiced

Why can't the Brexit deadlock in the UK parliament be solved with a plurality vote?



Converting a String to DateTime


Converting dd/mm/yyyy formatted string to Datetimehow do i convert string to datetime in c#String yy-MM-dd HH:mm:ss.SSS convert to datetime in C#Converting a string into date format in the code behindConvert dd/MM/yyyy hh:mm tt string date to C# dateMost efficient way to convert this string to DateTimehow to convert string to datetime in c#.netConvert string “2017-01-01T12:00:33:123456Z+02” to DateTimeConvert String To DateTime (d MM yyyy)Convert APRIL, 03/2013 string to DateTime in C#What is the difference between String and string in C#?How do I enumerate an enum in C#?How do you set a default value for a MySQL Datetime column?How do you get a timestamp in JavaScript?How do you convert a byte array to a hexadecimal string, and vice versa?Should I use the datetime or timestamp data type in MySQL?Case insensitive 'Contains(string)'Converting string into datetimeHow do I get a consistent byte representation of strings in C# without manually specifying an encoding?C# DateTime to “YYYYMMDDHHMMSS” format













496















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










share|improve this question



















  • 1





    @dban Why a response from @CMS not marked as an answer? There may be a reason -I'm curious.

    – nam
    May 7 '17 at 16:49






  • 1





    How to convert dd/mm/yyyy to mm/dd/yyyy?

    – ragu
    Jun 6 '17 at 7:15






  • 4





    @nam User deleted his account, or got banned, can't click on it nor see reputation/medals. Sadly all we can do is to give him some thumbs up.

    – YumeYume
    Aug 14 '17 at 14:23











  • How to convert string "yyyyMMdd" to datetime?

    – saulyasar
    Oct 19 '17 at 18:18















496















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










share|improve this question



















  • 1





    @dban Why a response from @CMS not marked as an answer? There may be a reason -I'm curious.

    – nam
    May 7 '17 at 16:49






  • 1





    How to convert dd/mm/yyyy to mm/dd/yyyy?

    – ragu
    Jun 6 '17 at 7:15






  • 4





    @nam User deleted his account, or got banned, can't click on it nor see reputation/medals. Sadly all we can do is to give him some thumbs up.

    – YumeYume
    Aug 14 '17 at 14:23











  • How to convert string "yyyyMMdd" to datetime?

    – saulyasar
    Oct 19 '17 at 18:18













496












496








496


73






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










share|improve this question
















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







c# datetime






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 13 '15 at 19:17









cramopy

2,92752137




2,92752137










asked May 28 '09 at 5:01







dban














  • 1





    @dban Why a response from @CMS not marked as an answer? There may be a reason -I'm curious.

    – nam
    May 7 '17 at 16:49






  • 1





    How to convert dd/mm/yyyy to mm/dd/yyyy?

    – ragu
    Jun 6 '17 at 7:15






  • 4





    @nam User deleted his account, or got banned, can't click on it nor see reputation/medals. Sadly all we can do is to give him some thumbs up.

    – YumeYume
    Aug 14 '17 at 14:23











  • How to convert string "yyyyMMdd" to datetime?

    – saulyasar
    Oct 19 '17 at 18:18












  • 1





    @dban Why a response from @CMS not marked as an answer? There may be a reason -I'm curious.

    – nam
    May 7 '17 at 16:49






  • 1





    How to convert dd/mm/yyyy to mm/dd/yyyy?

    – ragu
    Jun 6 '17 at 7:15






  • 4





    @nam User deleted his account, or got banned, can't click on it nor see reputation/medals. Sadly all we can do is to give him some thumbs up.

    – YumeYume
    Aug 14 '17 at 14:23











  • How to convert string "yyyyMMdd" to datetime?

    – saulyasar
    Oct 19 '17 at 18:18







1




1





@dban Why a response from @CMS not marked as an answer? There may be a reason -I'm curious.

– nam
May 7 '17 at 16:49





@dban Why a response from @CMS not marked as an answer? There may be a reason -I'm curious.

– nam
May 7 '17 at 16:49




1




1





How to convert dd/mm/yyyy to mm/dd/yyyy?

– ragu
Jun 6 '17 at 7:15





How to convert dd/mm/yyyy to mm/dd/yyyy?

– ragu
Jun 6 '17 at 7:15




4




4





@nam User deleted his account, or got banned, can't click on it nor see reputation/medals. Sadly all we can do is to give him some thumbs up.

– YumeYume
Aug 14 '17 at 14:23





@nam User deleted his account, or got banned, can't click on it nor see reputation/medals. Sadly all we can do is to give him some thumbs up.

– YumeYume
Aug 14 '17 at 14:23













How to convert string "yyyyMMdd" to datetime?

– saulyasar
Oct 19 '17 at 18:18





How to convert string "yyyyMMdd" to datetime?

– saulyasar
Oct 19 '17 at 18:18












13 Answers
13






active

oldest

votes


















671














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:



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





share|improve this answer




















  • 4





    Good eyes. I didn't see the comma in the OP.

    – lc.
    May 28 '09 at 7:09











  • (I think you meant to use a comma in the date and format strings, though, right?)

    – lc.
    May 28 '09 at 7:10











  • Edited... Yes, that's what I meant...

    – CMS
    May 28 '09 at 7:58






  • 1





    It is only a comma because of the OPs European Locale setting, what if you take that code to another server with a US.Locale, then the fractions of a section will be a decimal not a comma on the saved string, and your solution will break. Make sure you add a check for the type of incoming datetime string for its correct Locale before applying the correct parser. I'm surprised that Microsoft doesn't already have this code prebuild somewhere else in the CLR or C#.net

    – hamish
    Aug 24 '14 at 23:54











  • I copy this example and I've a functional error because today is 08 May :D LOL Thanks a lot CMS!

    – MacGyver
    May 9 '16 at 22:30


















218














You have basically two options for this. DateTime.Parse() and 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.



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 null specifies that the current culture should be used for parsing the string.






share|improve this answer






























    110














    try this



    DateTime myDate = DateTime.Parse(dateString);


    a better way would be this:



    DateTime myDate;
    if (!DateTime.TryParse(dateString, out myDate))

    // handle parse failure






    share|improve this answer
































      25














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



      Working and improved full source example is here: 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)));








      share|improve this answer
































        19














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



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





        share|improve this answer























        • No one mentioned that it only works with that particular format.

          – T.Todua
          Sep 18 '17 at 16:02











        • Pity... 🙂 Coders always think fellow coders will figure out... Good thing actually... Make us think more...

          – Krishna
          Nov 3 '18 at 10:00


















        19














        use DateTime.Parse(string)



        DateTime dateTime= DateTime.Parse(dateTimeStr);





        share|improve this answer
































          18














          Convert.ToDateTime or DateTime.Parse






          share|improve this answer
































            15














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





            share|improve this answer




















            • 1





              You missed the time part? I need both date & time, How can I do that?

              – Badhon Jain
              Sep 29 '14 at 16:04


















            14














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



            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






            share|improve this answer






























              14














              I tried various ways. What worked for me was this:



              Convert.ToDateTime(data, CultureInfo.InvariantCulture);


              data for me was times like this 9/24/2017 9:31:34 AM






              share|improve this answer























              • Thanks, it's working fine :))

                – Fox
                Apr 3 '18 at 15:07











              • It worked for me also. Thanks

                – Anish
                Aug 22 '18 at 14:22


















              3














              DateTime.Parse



              Syntax:



              DateTime.Parse(String value)
              DateTime.Parse(String value, IFormatProvider provider)
              DateTime.Parse(String value, IFormatProvider provider, DateTypeStyles styles)


              Example:



              string value = "1 January 2019";
              CultureInfo provider = new CultureInfo("en-GB");
              DateTime.Parse(value, provider, DateTimeStyles.NoCurrentDateDefault););


              • Value: string representation of date and time.

              • Provider: object which provides culture specific info.

              • Styles: formatting options that customize string parsing for some date and time parsing methods. For instance, AllowWhiteSpaces is a value which helps to ignore all spaces present in string while it parse.

              It's also worth remembering DateTime is an object that is stored as number internally in the framework, Format only applies to it when you convert it back to string.



              • Parsing converting a string to the internal number type.


              • Formatting converting the internal numeric value to a readable
                string.


              I recently had an issue where I was trying to convert a DateTime to pass to Linq what I hadn't realised at the time was format is irrelevant when passing DateTime to a Linq Query.



              DateTime SearchDate = DateTime.Parse(searchDate);
              applicationsUsages = applicationsUsages.Where(x => DbFunctions.TruncateTime(x.dateApplicationSelected) == SearchDate.Date);


              Full DateTime Documentation






              share|improve this answer
































                1














                Different cultures in the world write date strings in different ways. For example, in the US 01/20/2008 is January 20th, 2008. In France this will throw an InvalidFormatException. This is because France reads date-times as Day/Month/Year, and in the US it is Month/Day/Year.



                Consequently, a string like 20/01/2008 will parse to January 20th, 2008 in France, and then throw an InvalidFormatException in the US.



                To determine your current culture settings, you can use System.Globalization.CultureInfo.CurrentCulture.



                string dateTime = "01/08/2008 14:50:50.42"; 
                DateTime dt = Convert.ToDateTime(dateTime);
                Console.WriteLine("Year: 0, Month: 1, Day: 2, Hour: 3, Minute: 4, Second: 5, Millisecond: 6",
                dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);





                share|improve this answer






























                  1














                  Put this code in a static class> 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('-', ':', '-');





                  share|improve this answer























                    protected by Community May 27 '15 at 16:41



                    Thank you for your interest in this question.
                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                    Would you like to answer one of these unanswered questions instead?













                    13 Answers
                    13






                    active

                    oldest

                    votes








                    13 Answers
                    13






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    671














                    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:



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





                    share|improve this answer




















                    • 4





                      Good eyes. I didn't see the comma in the OP.

                      – lc.
                      May 28 '09 at 7:09











                    • (I think you meant to use a comma in the date and format strings, though, right?)

                      – lc.
                      May 28 '09 at 7:10











                    • Edited... Yes, that's what I meant...

                      – CMS
                      May 28 '09 at 7:58






                    • 1





                      It is only a comma because of the OPs European Locale setting, what if you take that code to another server with a US.Locale, then the fractions of a section will be a decimal not a comma on the saved string, and your solution will break. Make sure you add a check for the type of incoming datetime string for its correct Locale before applying the correct parser. I'm surprised that Microsoft doesn't already have this code prebuild somewhere else in the CLR or C#.net

                      – hamish
                      Aug 24 '14 at 23:54











                    • I copy this example and I've a functional error because today is 08 May :D LOL Thanks a lot CMS!

                      – MacGyver
                      May 9 '16 at 22:30















                    671














                    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:



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





                    share|improve this answer




















                    • 4





                      Good eyes. I didn't see the comma in the OP.

                      – lc.
                      May 28 '09 at 7:09











                    • (I think you meant to use a comma in the date and format strings, though, right?)

                      – lc.
                      May 28 '09 at 7:10











                    • Edited... Yes, that's what I meant...

                      – CMS
                      May 28 '09 at 7:58






                    • 1





                      It is only a comma because of the OPs European Locale setting, what if you take that code to another server with a US.Locale, then the fractions of a section will be a decimal not a comma on the saved string, and your solution will break. Make sure you add a check for the type of incoming datetime string for its correct Locale before applying the correct parser. I'm surprised that Microsoft doesn't already have this code prebuild somewhere else in the CLR or C#.net

                      – hamish
                      Aug 24 '14 at 23:54











                    • I copy this example and I've a functional error because today is 08 May :D LOL Thanks a lot CMS!

                      – MacGyver
                      May 9 '16 at 22:30













                    671












                    671








                    671







                    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:



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





                    share|improve this answer















                    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:



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






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited May 31 '17 at 14:15









                    kame

                    6,6452076127




                    6,6452076127










                    answered May 28 '09 at 5:14









                    CMSCMS

                    600k162847815




                    600k162847815







                    • 4





                      Good eyes. I didn't see the comma in the OP.

                      – lc.
                      May 28 '09 at 7:09











                    • (I think you meant to use a comma in the date and format strings, though, right?)

                      – lc.
                      May 28 '09 at 7:10











                    • Edited... Yes, that's what I meant...

                      – CMS
                      May 28 '09 at 7:58






                    • 1





                      It is only a comma because of the OPs European Locale setting, what if you take that code to another server with a US.Locale, then the fractions of a section will be a decimal not a comma on the saved string, and your solution will break. Make sure you add a check for the type of incoming datetime string for its correct Locale before applying the correct parser. I'm surprised that Microsoft doesn't already have this code prebuild somewhere else in the CLR or C#.net

                      – hamish
                      Aug 24 '14 at 23:54











                    • I copy this example and I've a functional error because today is 08 May :D LOL Thanks a lot CMS!

                      – MacGyver
                      May 9 '16 at 22:30












                    • 4





                      Good eyes. I didn't see the comma in the OP.

                      – lc.
                      May 28 '09 at 7:09











                    • (I think you meant to use a comma in the date and format strings, though, right?)

                      – lc.
                      May 28 '09 at 7:10











                    • Edited... Yes, that's what I meant...

                      – CMS
                      May 28 '09 at 7:58






                    • 1





                      It is only a comma because of the OPs European Locale setting, what if you take that code to another server with a US.Locale, then the fractions of a section will be a decimal not a comma on the saved string, and your solution will break. Make sure you add a check for the type of incoming datetime string for its correct Locale before applying the correct parser. I'm surprised that Microsoft doesn't already have this code prebuild somewhere else in the CLR or C#.net

                      – hamish
                      Aug 24 '14 at 23:54











                    • I copy this example and I've a functional error because today is 08 May :D LOL Thanks a lot CMS!

                      – MacGyver
                      May 9 '16 at 22:30







                    4




                    4





                    Good eyes. I didn't see the comma in the OP.

                    – lc.
                    May 28 '09 at 7:09





                    Good eyes. I didn't see the comma in the OP.

                    – lc.
                    May 28 '09 at 7:09













                    (I think you meant to use a comma in the date and format strings, though, right?)

                    – lc.
                    May 28 '09 at 7:10





                    (I think you meant to use a comma in the date and format strings, though, right?)

                    – lc.
                    May 28 '09 at 7:10













                    Edited... Yes, that's what I meant...

                    – CMS
                    May 28 '09 at 7:58





                    Edited... Yes, that's what I meant...

                    – CMS
                    May 28 '09 at 7:58




                    1




                    1





                    It is only a comma because of the OPs European Locale setting, what if you take that code to another server with a US.Locale, then the fractions of a section will be a decimal not a comma on the saved string, and your solution will break. Make sure you add a check for the type of incoming datetime string for its correct Locale before applying the correct parser. I'm surprised that Microsoft doesn't already have this code prebuild somewhere else in the CLR or C#.net

                    – hamish
                    Aug 24 '14 at 23:54





                    It is only a comma because of the OPs European Locale setting, what if you take that code to another server with a US.Locale, then the fractions of a section will be a decimal not a comma on the saved string, and your solution will break. Make sure you add a check for the type of incoming datetime string for its correct Locale before applying the correct parser. I'm surprised that Microsoft doesn't already have this code prebuild somewhere else in the CLR or C#.net

                    – hamish
                    Aug 24 '14 at 23:54













                    I copy this example and I've a functional error because today is 08 May :D LOL Thanks a lot CMS!

                    – MacGyver
                    May 9 '16 at 22:30





                    I copy this example and I've a functional error because today is 08 May :D LOL Thanks a lot CMS!

                    – MacGyver
                    May 9 '16 at 22:30













                    218














                    You have basically two options for this. DateTime.Parse() and 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.



                    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 null specifies that the current culture should be used for parsing the string.






                    share|improve this answer



























                      218














                      You have basically two options for this. DateTime.Parse() and 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.



                      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 null specifies that the current culture should be used for parsing the string.






                      share|improve this answer

























                        218












                        218








                        218







                        You have basically two options for this. DateTime.Parse() and 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.



                        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 null specifies that the current culture should be used for parsing the string.






                        share|improve this answer













                        You have basically two options for this. DateTime.Parse() and 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.



                        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 null specifies that the current culture should be used for parsing the string.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered May 28 '09 at 5:12









                        SanderSander

                        20.6k34678




                        20.6k34678





















                            110














                            try this



                            DateTime myDate = DateTime.Parse(dateString);


                            a better way would be this:



                            DateTime myDate;
                            if (!DateTime.TryParse(dateString, out myDate))

                            // handle parse failure






                            share|improve this answer





























                              110














                              try this



                              DateTime myDate = DateTime.Parse(dateString);


                              a better way would be this:



                              DateTime myDate;
                              if (!DateTime.TryParse(dateString, out myDate))

                              // handle parse failure






                              share|improve this answer



























                                110












                                110








                                110







                                try this



                                DateTime myDate = DateTime.Parse(dateString);


                                a better way would be this:



                                DateTime myDate;
                                if (!DateTime.TryParse(dateString, out myDate))

                                // handle parse failure






                                share|improve this answer















                                try this



                                DateTime myDate = DateTime.Parse(dateString);


                                a better way would be this:



                                DateTime myDate;
                                if (!DateTime.TryParse(dateString, out myDate))

                                // handle parse failure







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited May 19 '15 at 17:03

























                                answered May 28 '09 at 5:03









                                gehsekkygehsekky

                                2,57221714




                                2,57221714





















                                    25














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



                                    Working and improved full source example is here: 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)));








                                    share|improve this answer





























                                      25














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



                                      Working and improved full source example is here: 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)));








                                      share|improve this answer



























                                        25












                                        25








                                        25







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



                                        Working and improved full source example is here: 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)));








                                        share|improve this answer















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



                                        Working and improved full source example is here: 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)));









                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited May 23 '17 at 11:55









                                        Community

                                        11




                                        11










                                        answered May 23 '15 at 11:55









                                        guneysusguneysus

                                        4,07612930




                                        4,07612930





















                                            19














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



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





                                            share|improve this answer























                                            • No one mentioned that it only works with that particular format.

                                              – T.Todua
                                              Sep 18 '17 at 16:02











                                            • Pity... 🙂 Coders always think fellow coders will figure out... Good thing actually... Make us think more...

                                              – Krishna
                                              Nov 3 '18 at 10:00















                                            19














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



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





                                            share|improve this answer























                                            • No one mentioned that it only works with that particular format.

                                              – T.Todua
                                              Sep 18 '17 at 16:02











                                            • Pity... 🙂 Coders always think fellow coders will figure out... Good thing actually... Make us think more...

                                              – Krishna
                                              Nov 3 '18 at 10:00













                                            19












                                            19








                                            19







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



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





                                            share|improve this answer













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



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






                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered Nov 7 '14 at 6:04









                                            KrishnaKrishna

                                            2,44811927




                                            2,44811927












                                            • No one mentioned that it only works with that particular format.

                                              – T.Todua
                                              Sep 18 '17 at 16:02











                                            • Pity... 🙂 Coders always think fellow coders will figure out... Good thing actually... Make us think more...

                                              – Krishna
                                              Nov 3 '18 at 10:00

















                                            • No one mentioned that it only works with that particular format.

                                              – T.Todua
                                              Sep 18 '17 at 16:02











                                            • Pity... 🙂 Coders always think fellow coders will figure out... Good thing actually... Make us think more...

                                              – Krishna
                                              Nov 3 '18 at 10:00
















                                            No one mentioned that it only works with that particular format.

                                            – T.Todua
                                            Sep 18 '17 at 16:02





                                            No one mentioned that it only works with that particular format.

                                            – T.Todua
                                            Sep 18 '17 at 16:02













                                            Pity... 🙂 Coders always think fellow coders will figure out... Good thing actually... Make us think more...

                                            – Krishna
                                            Nov 3 '18 at 10:00





                                            Pity... 🙂 Coders always think fellow coders will figure out... Good thing actually... Make us think more...

                                            – Krishna
                                            Nov 3 '18 at 10:00











                                            19














                                            use DateTime.Parse(string)



                                            DateTime dateTime= DateTime.Parse(dateTimeStr);





                                            share|improve this answer





























                                              19














                                              use DateTime.Parse(string)



                                              DateTime dateTime= DateTime.Parse(dateTimeStr);





                                              share|improve this answer



























                                                19












                                                19








                                                19







                                                use DateTime.Parse(string)



                                                DateTime dateTime= DateTime.Parse(dateTimeStr);





                                                share|improve this answer















                                                use DateTime.Parse(string)



                                                DateTime dateTime= DateTime.Parse(dateTimeStr);






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Jul 6 '18 at 6:45

























                                                answered Nov 21 '16 at 9:57









                                                Amir TwitoAmir Twito

                                                82311616




                                                82311616





















                                                    18














                                                    Convert.ToDateTime or DateTime.Parse






                                                    share|improve this answer





























                                                      18














                                                      Convert.ToDateTime or DateTime.Parse






                                                      share|improve this answer



























                                                        18












                                                        18








                                                        18







                                                        Convert.ToDateTime or DateTime.Parse






                                                        share|improve this answer















                                                        Convert.ToDateTime or DateTime.Parse







                                                        share|improve this answer














                                                        share|improve this answer



                                                        share|improve this answer








                                                        edited Aug 24 '16 at 13:01









                                                        Bharat Gupta

                                                        1,1931123




                                                        1,1931123










                                                        answered May 28 '09 at 5:03









                                                        lc.lc.

                                                        89.8k19128157




                                                        89.8k19128157





















                                                            15














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





                                                            share|improve this answer




















                                                            • 1





                                                              You missed the time part? I need both date & time, How can I do that?

                                                              – Badhon Jain
                                                              Sep 29 '14 at 16:04















                                                            15














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





                                                            share|improve this answer




















                                                            • 1





                                                              You missed the time part? I need both date & time, How can I do that?

                                                              – Badhon Jain
                                                              Sep 29 '14 at 16:04













                                                            15












                                                            15








                                                            15







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





                                                            share|improve this answer















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






                                                            share|improve this answer














                                                            share|improve this answer



                                                            share|improve this answer








                                                            edited Sep 19 '11 at 8:06









                                                            Edwin de Koning

                                                            11.8k64566




                                                            11.8k64566










                                                            answered Sep 18 '11 at 11:41









                                                            Umair BaigUmair Baig

                                                            15112




                                                            15112







                                                            • 1





                                                              You missed the time part? I need both date & time, How can I do that?

                                                              – Badhon Jain
                                                              Sep 29 '14 at 16:04












                                                            • 1





                                                              You missed the time part? I need both date & time, How can I do that?

                                                              – Badhon Jain
                                                              Sep 29 '14 at 16:04







                                                            1




                                                            1





                                                            You missed the time part? I need both date & time, How can I do that?

                                                            – Badhon Jain
                                                            Sep 29 '14 at 16:04





                                                            You missed the time part? I need both date & time, How can I do that?

                                                            – Badhon Jain
                                                            Sep 29 '14 at 16:04











                                                            14














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



                                                            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






                                                            share|improve this answer



























                                                              14














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



                                                              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






                                                              share|improve this answer

























                                                                14












                                                                14








                                                                14







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



                                                                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






                                                                share|improve this answer













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



                                                                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







                                                                share|improve this answer












                                                                share|improve this answer



                                                                share|improve this answer










                                                                answered Apr 14 '15 at 13:07









                                                                dev.bvdev.bv

                                                                850916




                                                                850916





















                                                                    14














                                                                    I tried various ways. What worked for me was this:



                                                                    Convert.ToDateTime(data, CultureInfo.InvariantCulture);


                                                                    data for me was times like this 9/24/2017 9:31:34 AM






                                                                    share|improve this answer























                                                                    • Thanks, it's working fine :))

                                                                      – Fox
                                                                      Apr 3 '18 at 15:07











                                                                    • It worked for me also. Thanks

                                                                      – Anish
                                                                      Aug 22 '18 at 14:22















                                                                    14














                                                                    I tried various ways. What worked for me was this:



                                                                    Convert.ToDateTime(data, CultureInfo.InvariantCulture);


                                                                    data for me was times like this 9/24/2017 9:31:34 AM






                                                                    share|improve this answer























                                                                    • Thanks, it's working fine :))

                                                                      – Fox
                                                                      Apr 3 '18 at 15:07











                                                                    • It worked for me also. Thanks

                                                                      – Anish
                                                                      Aug 22 '18 at 14:22













                                                                    14












                                                                    14








                                                                    14







                                                                    I tried various ways. What worked for me was this:



                                                                    Convert.ToDateTime(data, CultureInfo.InvariantCulture);


                                                                    data for me was times like this 9/24/2017 9:31:34 AM






                                                                    share|improve this answer













                                                                    I tried various ways. What worked for me was this:



                                                                    Convert.ToDateTime(data, CultureInfo.InvariantCulture);


                                                                    data for me was times like this 9/24/2017 9:31:34 AM







                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Mar 18 '18 at 23:03









                                                                    zeiljazeilja

                                                                    31136




                                                                    31136












                                                                    • Thanks, it's working fine :))

                                                                      – Fox
                                                                      Apr 3 '18 at 15:07











                                                                    • It worked for me also. Thanks

                                                                      – Anish
                                                                      Aug 22 '18 at 14:22

















                                                                    • Thanks, it's working fine :))

                                                                      – Fox
                                                                      Apr 3 '18 at 15:07











                                                                    • It worked for me also. Thanks

                                                                      – Anish
                                                                      Aug 22 '18 at 14:22
















                                                                    Thanks, it's working fine :))

                                                                    – Fox
                                                                    Apr 3 '18 at 15:07





                                                                    Thanks, it's working fine :))

                                                                    – Fox
                                                                    Apr 3 '18 at 15:07













                                                                    It worked for me also. Thanks

                                                                    – Anish
                                                                    Aug 22 '18 at 14:22





                                                                    It worked for me also. Thanks

                                                                    – Anish
                                                                    Aug 22 '18 at 14:22











                                                                    3














                                                                    DateTime.Parse



                                                                    Syntax:



                                                                    DateTime.Parse(String value)
                                                                    DateTime.Parse(String value, IFormatProvider provider)
                                                                    DateTime.Parse(String value, IFormatProvider provider, DateTypeStyles styles)


                                                                    Example:



                                                                    string value = "1 January 2019";
                                                                    CultureInfo provider = new CultureInfo("en-GB");
                                                                    DateTime.Parse(value, provider, DateTimeStyles.NoCurrentDateDefault););


                                                                    • Value: string representation of date and time.

                                                                    • Provider: object which provides culture specific info.

                                                                    • Styles: formatting options that customize string parsing for some date and time parsing methods. For instance, AllowWhiteSpaces is a value which helps to ignore all spaces present in string while it parse.

                                                                    It's also worth remembering DateTime is an object that is stored as number internally in the framework, Format only applies to it when you convert it back to string.



                                                                    • Parsing converting a string to the internal number type.


                                                                    • Formatting converting the internal numeric value to a readable
                                                                      string.


                                                                    I recently had an issue where I was trying to convert a DateTime to pass to Linq what I hadn't realised at the time was format is irrelevant when passing DateTime to a Linq Query.



                                                                    DateTime SearchDate = DateTime.Parse(searchDate);
                                                                    applicationsUsages = applicationsUsages.Where(x => DbFunctions.TruncateTime(x.dateApplicationSelected) == SearchDate.Date);


                                                                    Full DateTime Documentation






                                                                    share|improve this answer





























                                                                      3














                                                                      DateTime.Parse



                                                                      Syntax:



                                                                      DateTime.Parse(String value)
                                                                      DateTime.Parse(String value, IFormatProvider provider)
                                                                      DateTime.Parse(String value, IFormatProvider provider, DateTypeStyles styles)


                                                                      Example:



                                                                      string value = "1 January 2019";
                                                                      CultureInfo provider = new CultureInfo("en-GB");
                                                                      DateTime.Parse(value, provider, DateTimeStyles.NoCurrentDateDefault););


                                                                      • Value: string representation of date and time.

                                                                      • Provider: object which provides culture specific info.

                                                                      • Styles: formatting options that customize string parsing for some date and time parsing methods. For instance, AllowWhiteSpaces is a value which helps to ignore all spaces present in string while it parse.

                                                                      It's also worth remembering DateTime is an object that is stored as number internally in the framework, Format only applies to it when you convert it back to string.



                                                                      • Parsing converting a string to the internal number type.


                                                                      • Formatting converting the internal numeric value to a readable
                                                                        string.


                                                                      I recently had an issue where I was trying to convert a DateTime to pass to Linq what I hadn't realised at the time was format is irrelevant when passing DateTime to a Linq Query.



                                                                      DateTime SearchDate = DateTime.Parse(searchDate);
                                                                      applicationsUsages = applicationsUsages.Where(x => DbFunctions.TruncateTime(x.dateApplicationSelected) == SearchDate.Date);


                                                                      Full DateTime Documentation






                                                                      share|improve this answer



























                                                                        3












                                                                        3








                                                                        3







                                                                        DateTime.Parse



                                                                        Syntax:



                                                                        DateTime.Parse(String value)
                                                                        DateTime.Parse(String value, IFormatProvider provider)
                                                                        DateTime.Parse(String value, IFormatProvider provider, DateTypeStyles styles)


                                                                        Example:



                                                                        string value = "1 January 2019";
                                                                        CultureInfo provider = new CultureInfo("en-GB");
                                                                        DateTime.Parse(value, provider, DateTimeStyles.NoCurrentDateDefault););


                                                                        • Value: string representation of date and time.

                                                                        • Provider: object which provides culture specific info.

                                                                        • Styles: formatting options that customize string parsing for some date and time parsing methods. For instance, AllowWhiteSpaces is a value which helps to ignore all spaces present in string while it parse.

                                                                        It's also worth remembering DateTime is an object that is stored as number internally in the framework, Format only applies to it when you convert it back to string.



                                                                        • Parsing converting a string to the internal number type.


                                                                        • Formatting converting the internal numeric value to a readable
                                                                          string.


                                                                        I recently had an issue where I was trying to convert a DateTime to pass to Linq what I hadn't realised at the time was format is irrelevant when passing DateTime to a Linq Query.



                                                                        DateTime SearchDate = DateTime.Parse(searchDate);
                                                                        applicationsUsages = applicationsUsages.Where(x => DbFunctions.TruncateTime(x.dateApplicationSelected) == SearchDate.Date);


                                                                        Full DateTime Documentation






                                                                        share|improve this answer















                                                                        DateTime.Parse



                                                                        Syntax:



                                                                        DateTime.Parse(String value)
                                                                        DateTime.Parse(String value, IFormatProvider provider)
                                                                        DateTime.Parse(String value, IFormatProvider provider, DateTypeStyles styles)


                                                                        Example:



                                                                        string value = "1 January 2019";
                                                                        CultureInfo provider = new CultureInfo("en-GB");
                                                                        DateTime.Parse(value, provider, DateTimeStyles.NoCurrentDateDefault););


                                                                        • Value: string representation of date and time.

                                                                        • Provider: object which provides culture specific info.

                                                                        • Styles: formatting options that customize string parsing for some date and time parsing methods. For instance, AllowWhiteSpaces is a value which helps to ignore all spaces present in string while it parse.

                                                                        It's also worth remembering DateTime is an object that is stored as number internally in the framework, Format only applies to it when you convert it back to string.



                                                                        • Parsing converting a string to the internal number type.


                                                                        • Formatting converting the internal numeric value to a readable
                                                                          string.


                                                                        I recently had an issue where I was trying to convert a DateTime to pass to Linq what I hadn't realised at the time was format is irrelevant when passing DateTime to a Linq Query.



                                                                        DateTime SearchDate = DateTime.Parse(searchDate);
                                                                        applicationsUsages = applicationsUsages.Where(x => DbFunctions.TruncateTime(x.dateApplicationSelected) == SearchDate.Date);


                                                                        Full DateTime Documentation







                                                                        share|improve this answer














                                                                        share|improve this answer



                                                                        share|improve this answer








                                                                        edited Feb 27 at 11:29

























                                                                        answered Feb 27 at 10:43









                                                                        Mr.BMr.B

                                                                        8711




                                                                        8711





















                                                                            1














                                                                            Different cultures in the world write date strings in different ways. For example, in the US 01/20/2008 is January 20th, 2008. In France this will throw an InvalidFormatException. This is because France reads date-times as Day/Month/Year, and in the US it is Month/Day/Year.



                                                                            Consequently, a string like 20/01/2008 will parse to January 20th, 2008 in France, and then throw an InvalidFormatException in the US.



                                                                            To determine your current culture settings, you can use System.Globalization.CultureInfo.CurrentCulture.



                                                                            string dateTime = "01/08/2008 14:50:50.42"; 
                                                                            DateTime dt = Convert.ToDateTime(dateTime);
                                                                            Console.WriteLine("Year: 0, Month: 1, Day: 2, Hour: 3, Minute: 4, Second: 5, Millisecond: 6",
                                                                            dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);





                                                                            share|improve this answer



























                                                                              1














                                                                              Different cultures in the world write date strings in different ways. For example, in the US 01/20/2008 is January 20th, 2008. In France this will throw an InvalidFormatException. This is because France reads date-times as Day/Month/Year, and in the US it is Month/Day/Year.



                                                                              Consequently, a string like 20/01/2008 will parse to January 20th, 2008 in France, and then throw an InvalidFormatException in the US.



                                                                              To determine your current culture settings, you can use System.Globalization.CultureInfo.CurrentCulture.



                                                                              string dateTime = "01/08/2008 14:50:50.42"; 
                                                                              DateTime dt = Convert.ToDateTime(dateTime);
                                                                              Console.WriteLine("Year: 0, Month: 1, Day: 2, Hour: 3, Minute: 4, Second: 5, Millisecond: 6",
                                                                              dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);





                                                                              share|improve this answer

























                                                                                1












                                                                                1








                                                                                1







                                                                                Different cultures in the world write date strings in different ways. For example, in the US 01/20/2008 is January 20th, 2008. In France this will throw an InvalidFormatException. This is because France reads date-times as Day/Month/Year, and in the US it is Month/Day/Year.



                                                                                Consequently, a string like 20/01/2008 will parse to January 20th, 2008 in France, and then throw an InvalidFormatException in the US.



                                                                                To determine your current culture settings, you can use System.Globalization.CultureInfo.CurrentCulture.



                                                                                string dateTime = "01/08/2008 14:50:50.42"; 
                                                                                DateTime dt = Convert.ToDateTime(dateTime);
                                                                                Console.WriteLine("Year: 0, Month: 1, Day: 2, Hour: 3, Minute: 4, Second: 5, Millisecond: 6",
                                                                                dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);





                                                                                share|improve this answer













                                                                                Different cultures in the world write date strings in different ways. For example, in the US 01/20/2008 is January 20th, 2008. In France this will throw an InvalidFormatException. This is because France reads date-times as Day/Month/Year, and in the US it is Month/Day/Year.



                                                                                Consequently, a string like 20/01/2008 will parse to January 20th, 2008 in France, and then throw an InvalidFormatException in the US.



                                                                                To determine your current culture settings, you can use System.Globalization.CultureInfo.CurrentCulture.



                                                                                string dateTime = "01/08/2008 14:50:50.42"; 
                                                                                DateTime dt = Convert.ToDateTime(dateTime);
                                                                                Console.WriteLine("Year: 0, Month: 1, Day: 2, Hour: 3, Minute: 4, Second: 5, Millisecond: 6",
                                                                                dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);






                                                                                share|improve this answer












                                                                                share|improve this answer



                                                                                share|improve this answer










                                                                                answered Oct 24 '17 at 13:22









                                                                                Saeed DiniSaeed Dini

                                                                                95122




                                                                                95122





















                                                                                    1














                                                                                    Put this code in a static class> 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('-', ':', '-');





                                                                                    share|improve this answer





























                                                                                      1














                                                                                      Put this code in a static class> 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('-', ':', '-');





                                                                                      share|improve this answer



























                                                                                        1












                                                                                        1








                                                                                        1







                                                                                        Put this code in a static class> 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('-', ':', '-');





                                                                                        share|improve this answer















                                                                                        Put this code in a static class> 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('-', ':', '-');






                                                                                        share|improve this answer














                                                                                        share|improve this answer



                                                                                        share|improve this answer








                                                                                        edited Aug 8 '18 at 15:46

























                                                                                        answered Feb 23 '17 at 17:50









                                                                                        M.R.T2017M.R.T2017

                                                                                        302313




                                                                                        302313















                                                                                            protected by Community May 27 '15 at 16:41



                                                                                            Thank you for your interest in this question.
                                                                                            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                            Would you like to answer one of these unanswered questions instead?



                                                                                            Popular posts from this blog

                                                                                            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

                                                                                            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                                                                                            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived