Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Date Time in C#, Getting wrong output

Tags:

c#

I am trying to parse the date by using below code

DateTime mydate = DateTime.ParseExact(datetoconvert,"dd/mm/yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat); 

but its output is wrong, the datetoconvert in above code is 30/Mar/2017 but output is 29/Jan/2017

looking forward for your valuable answers...

like image 640
Isham Khan Avatar asked Mar 30 '17 07:03

Isham Khan


People also ask

What is parse date time?

The Date. parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.

Which is an example of correctly parsing a date time string into a DateTime object in net?

DateTime dateTime10 = DateTime. ParseExact(dateString, "mm/dd/yyyy", provider); dateString = "not a date"; // Exception: The string was not recognized as a valid DateTime.


3 Answers

Lowercase mm means minute, use MM

DateTime mydate = DateTime.ParseExact(datetoconvert,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat); 

If you want to output it as 30/Mar/2017(different topic):

string result = mydate.ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture);

But note that / has a special meaning too(in Parse and ToString). It will be replaced with your current cultures date-separator which seems to be / but fails with a different. You can avoid it by specifying CultureInfo.InvariantCulture or by masking it by wrapping it with apostrophes:

DateTime mydate = DateTime.ParseExact(datetoconvert,"dd'/'MM'/'yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat); 
like image 99
Tim Schmelter Avatar answered Oct 11 '22 11:10

Tim Schmelter


replace

"dd/mm/yyyy" 

with

"dd/MMM/yyyy" 

because "Jan" is matched by MMM instead of mm (for minutes)

Reference

"MMM" The abbreviated name of the month.

https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

like image 7
fubo Avatar answered Oct 11 '22 13:10

fubo


The date format is wrong. try "dd/MM/yyyy" instead of "dd/mm/yyyy"

If you need abbrivated month name, use "dd/MMM/yyyy"

like image 1
Santhosh Avatar answered Oct 11 '22 11:10

Santhosh