Datetime format Issue: String was not recognized as a valid DateTime - c#

I want to format the input string into MM/dd/yyyy hh:mm:ss format in C#.
The input string is in format MM/dd/yyyy hh:mm:ss
For example :"04/30/2013 23:00"
I tried Convert.ToDateTime() function, but it considers 4 as date and 3 as month which is not what I want. Actually month is 04 and date is 03.
I tried DateTime.ParseExact() function also, But getting Exception.
I am getting error:
String was not recognized as a valid DateTime.

Your date time string doesn't contains any seconds. You need to reflect that in your format (remove the :ss).
Also, you need to specify H instead of h if you are using 24 hour times:
DateTime.ParseExact("04/30/2013 23:00", "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)
See here for more information:
Custom Date and Time Format Strings

You can use DateTime.ParseExact() method.
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format and culture-specific
format information. The format of the string representation must match
the specified format exactly.
DateTime date = DateTime.ParseExact("04/30/2013 23:00",
"MM/dd/yyyy HH:mm",
CultureInfo.InvariantCulture);
Here is a DEMO.
hh is for 12-hour clock from 01 to 12, HH is for 24-hour clock from 00 to 23.
For more information, check Custom Date and Time Format Strings

try this:
string strTime = "04/30/2013 23:00";
DateTime dtTime;
if(DateTime.TryParseExact(strTime, "MM/dd/yyyy HH:mm",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out dtTime))
{
Console.WriteLine(dtTime);
}

This can also be the problem if your string is 6/15/2019. DateTime Parse expects it to be 06/15/2019.
So first split it by slash
var dateParts = "6/15/2019"
var month = dateParts[0].PadLeft(2, '0');
var day = dateParts[1].PadLeft(2, '0');
var year = dateParts[2]
var properFormat = month + "/" +day +"/" + year;
Now you can use DateTime.Parse(properFormat, "MM/dd/yyyy"). It is very strange but this is only thing working for me.

change the culture and try out like this might work for you
string[] formats= { "MM/dd/yyyy HH:mm" }
var dateTime = DateTime.ParseExact("04/30/2013 23:00",
formats, new CultureInfo("en-US"), DateTimeStyles.None);
Check for details : DateTime.ParseExact Method (String, String[], IFormatProvider, DateTimeStyles)

DateTime dt1 = DateTime.ParseExact([YourDate], "dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Note the use of HH (24-hour clock) rather than hh (12-hour clock), and the use of InvariantCulture because some cultures use separators other than slash.
For example, if the culture is de-DE, the format "dd/MM/yyyy" would expect period as a separator (31.01.2011).

Below code worked for me:
string _stDate = Convert.ToDateTime(DateTime.Today.AddMonths(-12)).ToString("MM/dd/yyyy");
String format ="MM/dd/yyyy";
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
DateTime _Startdate = DateTime.ParseExact(_stDate, format, culture);

You may use this type format (get formatted data from sql server)
FORMAT(convert(datetime,'16/04/2018 10:52:20',103),'dd/MM/yyyy HH:mm:ss', 'en-us')
CONVERT(VARCHAR,convert(datetime,'16/04/2018 10:52:20',103), 120)

Related

Converting a String into a Valid DateTime Format

I have two Timestamps that are saved to and read from two XML files.
Currently I am reading the timestamps from the xml files in a WCF Service method, so they are coming in as Strings , but I need them to be converted into DateTime so they can be compared.
The obvious Convert.ToDateTime(TimeStampString) renders this error at Runtime -
String was not recognized as a valid DateTime
As does
DateTime.ParseExact(TimeStampString, "mm/dd/yyyy hh:MM:ss", CultureInfo.InvariantCulture);
Both Timestamps are in the correct format for DateTime (mm/dd/yyyy hh:MM:ss).
I've even tried splitting the timstamp strings into String[] and assembling my own DateTime object by hand, and I still received the error.
Is this a format issue? How can I make my String a valid DateTime?
It's a format issue
mm/dd/yy hh:MM:ss
should be
MM/dd/yyyy hh:mm:ss
(basically, swap the upper case MM in the date & the lowercase mm in the time)
I resolved the issue by removing any attempts to alter the format from US, so Strings came in with US format - then used an IFormatProvider to alter the format at conversion time.
IFormatProvider localFormat = new System.Globalization.CultureInfo("fr-FR", true);
DateTime ContentLastUpdatedTime = DateTime.Parse(ContentLastUpdatedStamp, localFormat , System.Globalization.DateTimeStyles.AssumeLocal);
DateTime ContentLastGrabbedTime = DateTime.Parse(LastGrabbedTimeStamp, localFormat , System.Globalization.DateTimeStyles.AssumeLocal);
You need to use
DateTime.ParseExact(TimeStampString, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
instead of
DateTime.ParseExact(TimeStampString, "mm/dd/yyyy hh:MM:ss", CultureInfo.InvariantCulture);
The issue is lower case mm which is used for minutes, You need MM upper case MM, plus your date is in 24 hours format, and you need upper case HH for hour part , so your format should be:
MM/dd/yyyy HH:mm:ss
(considering you have yyyy in your original code based on your comment)
See: Custom Date and Time Format Strings
Here you go
var dtedatetime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz");
DateTimeOffset dto;
bool bIsParsed = DateTimeOffset.TryParseExact(dtedatetime , "yyyy'-'MM'-'dd'T'HH':'mm':'sszzz",
System.Globalization.CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal, out dto);
var result = dto.DateTime;

Converting string to DateTime failing

I have a string variable whose data will be the format below.
18-03-2015 16:39:15
i'm trying to convert it to a valid DateTime with hour/minute/second but so far the line below fails.
DateTime dt = DateTime.ParseExact("18-03-2015 16:39:15", "dd-MM-yyyy h:m:s", CultureInfo.InvariantCulture);
You need to use uppercase H or HH, so "dd-MM-yyyy HH:m:s" with this time: 16:39:15.
See: The "HH" Custom Format Specifier
So lowercase is from 1 through 12 and uppercase for 24h format. If you use H or HH depends on if 4:39:15 is possible or 04:39:15. A single H supports both formats, so with or without a leading zero, whereas HH only allows 04:39:15.
It should be HH:mm:ss in format
DateTime dt = DateTime.ParseExact("18-03-2015 16:39:15", "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
// So: dt.ToString("dd-MM-yyyy HH:mm:ss") is 18-03-2015 16:39:15
Here are some examples of formatting the date with samples

DateTime.ParseExact throws System.FormatException

Why this line of code sometimes throws System.FormatException?
DateTime d = DateTime.ParseExact("01.07.2014", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Because your string and format doesn't match.
From documentation;
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format and culture-specific
format information. The format of the string representation must match
the specified format exactly.
Use dd.MM.yyyy format instead.
DateTime d = DateTime.ParseExact("01.07.2014",
"dd.MM.yyyy",
CultureInfo.InvariantCulture);
Here a demonstration.
Remember, "/" custom format specifier has a special meaning in custom date and time formats. It means as; replace me with the current culture date separator.
In your profile, it says you are from Azerbaijan. That means your CurrentCulture is probably az-Cyrl-AZ (Cyrillic, Azerbaijan) or az-Latn-AZ (Latin, Azerbaijan).
Actually, doesn't matter which culture you use on this case because both culture has . as a DateSeparator property.
That means your original code also works with your CurrentCulture.
DateTime d = DateTime.ParseExact("01.07.2014",
"dd/MM/yyyy",
CultureInfo.CurrentCulture);
// or you can use null
For more information, take a look;
Custom Date and Time Format Strings
You need a culture where "." is the DateSeparator, for example:
DateTime d = DateTime.ParseExact("01.07.2014", "dd/MM/yyyy",
CultureInfo.GetCultureInfo("az-Cyrl-AZ"));
if you are in Azerbaijan and use Azerbaijani language with the Cyrillic script.
You can use:
DateTime d = DateTime.ParseExact("01.07.2014", "dd/MM/yyyy",
null);
to just take the current culture.
Maybe you just need "d" instead of the verbose "dd/MM/yyyy", since the standard short date format in Azerbaijani is just like "01.07.2014".
The "invariant culture" uses "/" as its DateSeparator, so therefore you should not use it in your case.
Also, this works:
DateTime d = DateTime.ParseExact("01.07.2014", "dd/MM/yyyy",
new DateTimeFormatInfo { DateSeparator = ".", }
);
because new DateTimeFormatInfo() makes a read/write "invariant-culture" date/time info for which you can change the relevant property.
The / in the date format will match the date separator of the culture that you specify. If you use a culture that has period as date separator, the parsing will work.
Example:
DateTime d = DateTime.ParseExact("01.07.2014", "dd/MM/yyyy", CultureInfo.GetCultureInfo("de"));
You can also use a literal period instead of the date separator specificer, then it works with the invariant culture:
DateTime d = DateTime.ParseExact("01.07.2014", "dd.MM.yyyy", CultureInfo.InvariantCulture);
Ref: Custom Date and Time Format Strings
The format you have is different from the string provided:
Try either of the below, it will work :)
DateTime d1 = DateTime.ParseExact("01/07/2014", "dd/MM/yyyy", CultureInfo.InvariantCulture);
DateTime d2 = DateTime.ParseExact("01.07.2014", "dd.MM.yyyy", CultureInfo.InvariantCulture);
Problem:
Your separator in date is . while in string format it is /
Solution:
Your format should be "dd.MM.yyyy" or "MM.dd.yyyy" as your date is "01.07.2014". 01 and 07 exist both as date and month.
This date can be 01st July 2014 or 07 Jan 2014.
Your code should be
DateTime d = DateTime.ParseExact("01.07.2014",
"dd.MM.yyyy",
CultureInfo.InvariantCulture);
OR
DateTime d = DateTime.ParseExact("01.07.2014",
"MM.dd.yyyy",
CultureInfo.InvariantCulture);

DateTime.ParseExact strings to datetime

I'm about to begin cursing at my computer!
I have one program that output a datetime as a string, but I want to feed it into another as a datetime.
The string I get is on the form:
dd/MM/yy hh:mm:ss
And I would like to find an appropriate way to get a DateTime object back.
I'm thinking something like:
string date = "11/07/14 18:19:20";
string dateformat = "dd/MM/yy hh:mm:ss";
DateTime converted_date = DateTime.ParseExact(date,
dateformat, CultureInfo.InvariantCulture);
But several of the conversion of dates result in an Exception being thrown back with the message "Not valid timedate".
What am I missing?
'hh' for hour is actually 12 hour clock, 01-12. I think you want 'HH' or 'H' for 24-hour clock ('HH' is zero-padded, 'H' is not). Check out: http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx for specific formats.
The hour is not in 12-hour format. For 24-hour format, it's H.
string date = "11/07/14 18:19:20";
string dateformat = "dd/MM/yy H:mm:ss";
DateTime converted_date = DateTime.ParseExact(date,
dateformat, CultureInfo.InvariantCulture);

convert string to datetime format invalid System.Datetime

I have been trying many different solutions found here but none works. I want to convert the string to the format of dd/MM/yyyy
editField["ExpiryTime"] = "5/19/2011 12:00:00 AM";
DateTime dt = DateTime.ParseExact(editField["ExpiryTime"].ToString(), "dd/MM/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);
But I always get an error of invalid System.DateTime. Pleaes help!
Use CultureInfo.InvariantCulture to avoid culture issues like invalid date separators and this format:
M/dd/yyyy hh:mm:ss tt
Uppercase M is for months, dd are the days, yyyy the four digit years. Lowercase hh are the hours in 12h format(required in combination with AM/PM), mm are the minutes, ss the seconds and tt the AM/PM designator.
string input = editField["ExpiryTime"].ToString(); // "5/19/2011 12:00:00 AM"
DateTime dt = DateTime.ParseExact(input, "M/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
I want to convert the string to the format of dd/MM/yyyy
Then use ToString in the same way, CultureInfo.InvariantCulture forces / as date separator, without it will be replaced with your current culture's date-separator:
string result = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
If you need it as string, then you should try this
var dt = string.Format("{0:dd/MM/yyyy}",DateTime.Now);
Note: Also check your local system date time format. If it mismatches with the used one , still you might experience the same exception..

Categories