I am trying to convert to time from a string
My string are like this "11:45 AM" or "03:19 PM" and i am using
dateTime = DateTime.ParseExact("11:45 AM", "H:mm tt",
System.Globalization.CultureInfo.InvariantCulture);
Then it is getting converted but when i am passing
DateTime.ParseExact("3:19 PM", "H:mm tt",
System.Globalization.CultureInfo.InvariantCulture).ToString();
Getting error as
String was not recognized as a valid DateTime.
I cant understand why it is happening any one have idea then please help me
I would use h instead of H. H is for the 24hr fromat, h for the 12hr format.
DateTime.ParseExact("9:45 PM", "h:mm tt", System.Globalization.CultureInfo.InvariantCulture)
See the full list of format options here.
As you want to parse the 12 hr format and convert it to the 24 hr format then you can just use this
string dt = DateTime.ParseExact("3:19 PM", "h:mm tt",CultureInfo.InvariantCulture).ToString("HH:mm");;
Unfortunately, none of the answers are completely correct.
Ante meridiem and post meridiem belong to the 12-hour clock format. That's why you should never use 24-hour clock format specifiers if your string contains one of them.
That's why you need to use h or hh specifiers, not H or HH. Since your hour part can be with leading zeros, using hh specifier is the best option for both of your string types.
Using the hh:mm tt format will parse your strings successfully.
string s = "03:19 PM";
DateTime dt;
if(DateTime.TryParseExact(s, "hh:mm tt", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
dt.Dump(); // 29.05.2015 15:19:00
}
and
string s = "11:45 AM";
DateTime dt;
if(DateTime.TryParseExact(s, "hh:mm tt", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
dt.Dump(); // 29.05.2015 11:45:00
}
Also, you mentioned the 3:19 PM string in your code example. Since the hour part is single digit, you need to use the h:mm tt format in that case.
Invariant culture requires two-digit hours.
Related
I'm trying to remove hidden characters from a string that represents a date time. I'm using .Net Fiddle and you can see the line that tries to ParseExact fails.
Here is a snippet. Please refer to the fiddle link for working code.
var dateTime = "2015-04-14 07:30:00 PM"; //<= this throws an error from some hidden char
dateTime = Regex.Replace(dateTime, #"[^\w:\s-]", "");
Console.WriteLine(dateTime);
DateTime dateWithTime = DateTime.ParseExact(dateTime, "yyyy-MM-dd HH:mm:ss tt",
CultureInfo.InvariantCulture);
Console.WriteLine("OK");
The HH in the format string refers to the 24-hour clock hours, which doesn't work when using AM/PM in the format string for PM times.
Change HH to hh.
It's not an invisible character. Your use of HH conflicts with your use of tt. HH is 24 hour time, but you are using tt to interpret PM (12 hour time). Change it to hh and it works.
var dateTime = "2015-04-14 07:30:00 PM";
//dateTime = Regex.Replace(dateTime, #"[^\w:\s-]", ""); <= not needed
Console.WriteLine(dateTime);
DateTime dateWithTime = DateTime.ParseExact(dateTime, "yyyy-MM-dd hh:mm:ss tt",
CultureInfo.InvariantCulture);
Console.WriteLine("OK");
You need to change HH to hh.
yyyy-MM-dd hh:mm:ss tt
How can i parse a string like this: "2/22/2015 9:54:02 AM" to a DateTime instance?
i am currently using the DateTime.ParseExact method but without the AM/PM
i.e:
DateTime.ParseExact("2/22/2015 9:54:02", "M/dd/yyyy HH:mm:ss")
I would like to be able to parse the AM/PM signs as well.
You should change the hour format (H) to lowercase like this:
DateTime.ParseExact("2/22/2015 9:54:02 AM", "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
Uppercase "H" indicates a 24-hour time and lowercase "h" indicates 12-hour time and will respect the AM/PM in the candidate string.
You can use the tt specifier:
DateTime.ParseExact(
"2/22/2015 9:54:02 PM",
"M/dd/yyyy h:mm:ss tt",
CultureInfo.InvariantCulture
)
However be warned this can be locale specific. Also HH refers to the 24 hour clock, with AM/PM you generally use the 12 hour clock, so you'd want to use hh or just h for that.
Try This,
DateTime.ParseExact("2/22/2015 9:54:02 PM", "M/dd/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
try this:
if (date.Contains("AM") || date.Contains("PM"))
return DateTime.ParseExact(date, "dd.MM.yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
return DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture);
My Date Format : 12/30/2014 12:00:00 AM (MM/dd/yyyy) and I have a string rep as
String DateOfIssue = "12/30/2014 12:00:00 AM";
DateTime DOI = DateTime.ParseExact((DateOfIssue).Trim(), "MM/dd/yyyy HH:mm:ss tt", CultureInfo.GetCultureInfo("en-GB"));
but it is throwing exception. I have seen a lot of posts on SO but none is working. What am I doing wrong ? Please help and point my error. I have tried en-US also but that is also not working.
when I remove tt every thing works fine.
HH - is for 24 hours format, use hh instead:
DateTime DOI = DateTime.ParseExact((DateOfIssue).Trim(), "MM/dd/yyyy hh:mm:ss tt", CultureInfo.GetCultureInfo("en-GB"));
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..
I have the following date in string format "2011-29-01 12:00 am" . Now I am trying to convert that to datetime format with the following code:
DateTime.TryParse(dateTime, out dt);
But I am alwayws getting dt as {1/1/0001 12:00:00 AM} , Can you please tell me why ? and how can I convert that string to date.
EDIT: I just saw everybody mentioned to use format argument. I will mention now that I can't use the format parameter as I have some setting to select the custom dateformat what user wants, and based on that user is able to get the date in textbox in that format automatically via jQuery datepicker.
This should work based on your example "2011-29-01 12:00 am"
DateTime dt;
DateTime.TryParseExact(dateTime,
"yyyy-dd-MM hh:mm tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);
You need to use the ParseExact method. This takes a string as its second argument that specifies the format the datetime is in, for example:
// Parse date and time with custom specifier.
dateString = "2011-29-01 12:00 am";
format = "yyyy-dd-MM h:mm tt";
try
{
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
Console.WriteLine("{0} is not in the correct format.", dateString);
}
If the user can specify a format in the UI, then you need to translate that to a string you can pass into this method. You can do that by either allowing the user to enter the format string directly - though this means that the conversion is more likely to fail as they will enter an invalid format string - or having a combo box that presents them with the possible choices and you set up the format strings for these choices.
If it's likely that the input will be incorrect (user input for example) it would be better to use TryParseExact rather than use exceptions to handle the error case:
// Parse date and time with custom specifier.
dateString = "2011-29-01 12:00 am";
format = "yyyy-dd-MM h:mm tt";
DateTime result;
if (DateTime.TryParseExact(dateString, format, provider, DateTimeStyles.None, out result))
{
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
else
{
Console.WriteLine("{0} is not in the correct format.", dateString);
}
A better alternative might be to not present the user with a choice of date formats, but use the overload that takes an array of formats:
// A list of possible American date formats - swap M and d for European formats
string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm",
"MM/d/yyyy HH:mm:ss.ffffff" };
string dateString; // The string the date gets read into
try
{
dateValue = DateTime.ParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None);
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
If you read the possible formats out of a configuration file or database then you can add to these as you encounter all the different ways people want to enter dates.
The main drawback with this approach is that you will still have ambiguous dates. The formats are tried in order so no matter what it'll try the European format before the American (or vice versa) and cover anything where the day is less than 13 to a European formatted date even if the user thought they were entering an American formatted date.
Try using safe TryParseExact method
DateTime temp;
string date = "2011-29-01 12:00 am";
DateTime.TryParseExact(date, "yyyy-dd-MM hh:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out temp);
From DateTime on msdn:
Type: System.DateTime% When this method returns, contains the DateTime
value equivalent to the date and time contained in s, if the
conversion succeeded, or MinValue if the conversion failed. The
conversion fails if the s parameter is null, is an empty string (""),
or does not contain a valid string representation of a date and time.
This parameter is passed uninitialized.
Use parseexact with the format string "yyyy-dd-MM hh:mm tt" instead.
That works:
DateTime dt = DateTime.ParseExact("2011-29-01 12:00 am", "yyyy-dd-MM hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);
DateTime dt = DateTime.ParseExact("11-22-2012 12:00 am", "MM-dd-yyyy hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);
If you give the user the opportunity to change the date/time format, then you'll have to create a corresponding format string to use for parsing. If you know the possible date formats (i.e. the user has to select from a list), then this is much easier because you can create those format strings at compile time.
If you let the user do free-format design of the date/time format, then you'll have to create the corresponding DateTime format strings at runtime.