-2

I have date in string format 20/05/2016:

string weekEndDate="20/05/2016"

when convert it to DateTime,An error Occured:

DateTime EndDate = Convert.ToDateTime(weekEndDate);

String was not recognized as a valid DateTime.

MusicLovingIndianGirl
  • 5,909
  • 9
  • 34
  • 65
  • What is the culture on your server. Is it one that accepts dates in the format `dd/MM/yyyy`? –  May 20 '16 at 07:06
  • 1
    Possible duplicate of [Converting dd/mm/yyyy formatted string to Datetime](http://stackoverflow.com/questions/15738608/converting-dd-mm-yyyy-formatted-string-to-datetime) – Vibhesh Kaul May 20 '16 at 07:21

4 Answers4

0

Try changing your string format to "yyyy-mm-dd" or "yyyy/mm/dd"

Bharath theorare
  • 524
  • 7
  • 27
0

You can also use DateTime.TryParse method to parse date from any date format. See examples

Enn
  • 2,137
  • 15
  • 24
0

You can use ParseExact method to parse the string into DateTime.

string weekEndDate = "20/05/2016";
DateTime EndDate = DateTime.ParseExact(weekEndDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);

Or you can use TryParseExact it will not throw exception if string is not parsed into DateTime

DateTime.TryParseExact(weekEndDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out EndDate);
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40
0

Use TryParseExact

string d1 = "11/18/2016 11:45:44 AM";
string d2 = "11/18/2016 11:45:59 AM";

DateTime frmdate;
DateTime todate;
CultureInfo enUS = new CultureInfo("en-US");
bool f = DateTime.TryParseExact(d1, "M/dd/yyyy HH:mm:ss tt", enUS, DateTimeStyles.None, out frmdate);
bool t = DateTime.TryParseExact(d2, "M/dd/yyyy HH:mm:ss tt", enUS, DateTimeStyles.None, out todate);

TimeSpan val = frmdate - todate;
Hitesh
  • 3,449
  • 8
  • 39
  • 57
sakthi
  • 1
  • 1