I need to parse dates and times from strings. The Problem is that the strings can have any possible format. But I also get the format strings.
So i get:
Date = "9/15/2010"
Time = "16:12:45"
DateFormat = "M/dd/yyyy"
TimeFormat = "h:mm:ss"
TimeZone = "+2:00:00" // +/- and time in TimeFormat
But i have some problems parsing these strings.
I can't parse the time
DateTime.ParseExact("16:12:45","h:mm:ss",null,DateTimeStyles.None);
does not work and causes a FormatException. What is wrong with this call?
If the DateFormat contains slashes, i need to escape them #"M\/dd\/yyyy". Are there any other chars that would need escaping?
Can i parse the whole DateTime in one? Somehting like:
DateTime.ParseExact(Date+' '+Time+' '+TimeZone,DateFormat+' '+TimeFormat+' +'+TimeFormat,null,DateTimeStyles.None);
What is wrong with this call?
The "h:mm:ss" format string expects the hours element to be in 12-hour format (h); The hours in your string are in 24-hour format so you need to use H instead:
DateTime.ParseExact("16:12:45", "H:mm:ss", null, DateTimeStyles.None);
Are there any other chars that would need escaping?
Any literal character in your string that clashes with a format specifier will need to be escaped. For example, / is the date separator but \/ means the literal / character; : is the time separator but \: means the literal : character; y is one of the year specifiers but \y is the literal y character.
Can i parse the whole DateTime in one?
Yes.
How about this?
var #return = (DateTime?)null;
if (source != null)
{
source = source.Trim();
if (source.Length > 0)
{
var fs = new string[]
{
"d MMMM yyyy h:mm tt",
"d MMMM yyyy h:mm:ss tt",
"d MMMM yyyy HH:mm",
"d MMMM yyyy HH:mm:ss",
"d MMMM yyyy",
"d/M/yy h:mm tt",
"d/M/yy h:mm:ss tt",
"d/M/yy HH:mm",
"d/M/yy HH:mm:ss",
"d/M/yy",
"d/M/yyyy HH:mm",
"d/M/yyyy HH:mm:ss",
"d/M/yyyy h:mm:ss tt",
"d/M/yyyy",
"d/M/yyyy h:mm tt",
"d-MMMM-yy HH:mm",
"d-MMMM-yyyy h:mm tt",
"d-MMMM-yyyy h:mm:ss tt",
"d-MMMM-yyyy HH:mm",
"d-MMMM-yyyy HH:mm:ss",
"d-MMMM-yyyy",
"d-MMM-yy",
"d-MMM-yy h:mm tt",
"d-MMM-yy h:mm:ss tt",
"d-MMM-yy HH:mm",
"d-MMM-yy HH:mm:ss",
"d-MMM-yyyy",
"d-M-yy h:mm tt",
"d-M-yy h:mm:ss tt",
"d-M-yy HH:mm",
"d-M-yy HH:mm:ss",
"d-M-yy",
"d-M-yyyy",
"yyyy/M/d h:mm tt",
"yyyy/M/d h:mm:ss tt",
"yyyy/M/d HH:mm",
"yyyy/M/d HH:mm:ss",
"yyyy/M/d",
"yyyy-M-d h:mm tt",
"yyyy-M-d h:mm:ss tt",
"yyyy-M-d HH:mm",
"yyyy-M-d HH:mm:ss",
"yyyy-M-d",
"yyyy-MM-ddTHH:mm:ss",
};
#return = DateTime.ParseExact(source, fs,
System.Globalization.CultureInfo.CurrentCulture,
System.Globalization.DateTimeStyles.None);
}
}
return #return;
Do you know which culture the original string belongs to? If you do you can specify a culture specific DateTimeStyle when calling Parse()
DateTime date = DateTime.Parse("<your specific date>", System.Globalization.CultureInfo.GetCultureInfo("<your culture>").DateTimeFormat);
Create a custom DateTimeFormatInfo and pass that into DateTime.Parse. Like this:
string dateValue = string.Format("{0} {1}", "9/15/2010", "16:12:45");
var customDateTimeFormatInfo = new DateTimeFormatInfo();
customDateTimeFormatInfo.FullDateTimePattern = string.Format("{0} {1}", "M/dd/yyyy", "h:mm:ss");
DateTime dt = DateTime.Parse(dateValue, customDateTimeFormatInfo);
No escaping required and handled your "h:mm:ss" fine with no modification required.
Related
I want to convert string as : "25/12/2017 4:00 PM" to "12/25/2017 4:00 PM". My code :
var TDXRSC = "25/12/2017 4:00 PM";
DateTime.ParseExact(TDXRSC, "dd/MM/yyyy hh:mm tt", CultureInfo.InvariantCulture);
But it's not working.
The issue is your date format expected is dd/MM/yyyy hh:mm tt but the reference date only has a single digit hour 4. You are probably better off not expect leading zeros for days, months or hours.
Try..
var TDXRSC = "25/12/2017 4:00 PM";
var input = DateTime.ParseExact(TDXRSC, "dd/MM/yyyy h:mm tt", CultureInfo.InvariantCulture);
This will also still parse 2 digit hours. So var TDXRSC = "25/12/2017 12:00 PM"; will still parse correctly.
var TDXRSC = "25/12/2017 4:00 PM";
var input = DateTime.ParseExact(TDXRSC, "dd/MM/yyyy h:mm tt", CultureInfo.InvariantCulture);
var output = input.ToString("MM/dd/yyyy h:mm tt");
When you call ParseExact you're telling the compiler what format the incoming date is. You can then use ToString() method to provide a format for a string representation of the parsed date.
Hope that .TryParseExtract will be more safe to use for conversion, use like the following:
var dateString = "25/12/2017 4:00 PM";
DateTime inputDate;
if(DateTime.TryParseExact(dateString, "dd/MM/yyyy h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out inputDate))
{
var output = inputDate.ToString("MM/dd/yyyy hh:mm tt");
Console.WriteLine(output);
}
else
{
Console.WriteLine("Conversion failed");
}
Working Example
var TDXRSC = "25/12/2017 4:00 PM";
DateTime date = Convert.ToDateTime(TDXRSC);
string Format = date.ToString("MM/dd/yyyy h:mm tt");
I am trying to convert date time in 12/20/2013 17:40 format to the below format
20 Dec 2013 05:40 pm. How it's possible?
You need to use DateTime.TryParseExact. This should do it
string originalDate = "2/20/2013 17:40";
DateTime parsedDate;
if (DateTime.TryParseExact(originalDate, "M/dd/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
{
string requiredFormat = parsedDate.ToString("dd MMM yyyy hh:mm ttt");
}
OutPut:
20 Feb 2013 05:40 PM
mydatetime.ToString("dd MMM yyyy hh:mm tt");
dt.ToString("dd MMM yyyy hh:mm tt");
dateTime.ToString("dd MMM yyyy hh:mm tt");
Method 1: if you have datetime in String format
String str = "12/20/2013 17:40";//20 Dec 2013 05:40 pm
DateTime result;
string date="";
if (DateTime.TryParseExact(str, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
date=result.ToString("dd MMM yyyy hh:mm tt");
Method 2: if you have datetime in DateTime variable.
String strdatetime=datetime.ToString("dd MMM yyyy hh:mm tt");
DateTime time = DateTime.Now;
Console.WriteLine(time.ToString("dd MMM yyyy hh:mm tt"));
You can use format strings:
this is from 1 minute google:
http://www.csharp-examples.net/string-format-datetime/
http://www.dotnetperls.com/datetime-format
First of all, DateTime doesn't have a format, strings have..
If your 12/20/2013 17:40 is a DateTime, you can use DateTime.ToString(String, IFormatProvider) method to format it like;
date.ToString("dd MMM yyyy hh:mm tt", CultureInfo.InvariantCulture);
If your 12/20/2013 17:40 is a string, then you can use DateTime.ParseExact(String, String, IFormatProvider) method like;
string s = "12/20/2013 17:40";
var date = DateTime.ParseExact(s, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
Console.WriteLine(date.ToString("dd MMM yyyy hh:mm tt", CultureInfo.InvariantCulture));
Output will be;
20 Dec 2013 05:40 PM
Here a demonstration.
For more information, take a look at;
Custom Date and Time Format Strings
In C# 6.0 you can use string interpolation in order to display formatted dates.
DateTime date = DateTime.Parse("12/20/2013 17:40");
string formattedDate = $"{date: dd MMM yyyy hh:mm tt}";
There are lots of thread for this , but I am still blocked at the following:
What I have:
I am trying to build windows phone App which will pick Date of Birth of an individual
Code Behind:
string dateString = "";
DateTime dt = DateTime.Now;
if (value != null && DateTime.TryParse(value.ToString(), culture, DateTimeStyles.None, out dt))
{
if (dt.Equals(DateTime.MinValue))
{
//dateString = "mm/dd/yyyy";
return "";
}
else
return dt.ToShortDateString();
}
else
return dateString;
}
what I need:
I want it to parse any date format which should be culture Independent.
What I tried:
1.I tried using CultureInfo.InvariantCultute, CultureInfo.CurrentCulture
2.Tried using ExactParser as follows:
string[] formats = {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", "d/M/yyyy hh:mm:ss tt", "dd/MM/yyyy hh:mm:ss tt", "d/M/yyyy" , "dd/MM/yyyy" , "M/d/yyyy" ,"MM/dd/yyyy",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", "dd/MM/yyyy hh:mm:ss", "d/M/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", "d/M/yyyy hh:mm tt", "d/M/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm", "d/M/yyyy h:mm", "d/M/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm","dd/MM/yyyy hh:mm", "dd/M/yyyy hh:mm"};
if (value != null && DateTime.TryParseExact(value.ToString(), format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
but that is too hardcoded and will not cover several cases.
Is there any way to pick DOB in any format?
Any help would be Appreciated. Thanks!!
Not really, because everyone has their own date formatting.
What you're basically trying to do is magically deduce the dates from the second half of the above XKCD comic. ;)
That said, the only way you could TRY and do this, is to parse a string with every format you think it might be, and then make a sanity check in every case where a parse was successful. Said sanity check would be difficult however... Does 11-02 mean February 11th or November 2nd? You'd require some sort of context.
Sorry, but it seems impossible, since datetime could be ambiguous, and that's why misinterpreted e.g.
"01/02/03" is
01 Feb 2003 (Russia)
02 Jan 2003 (USA)
03 Feb 2001 (China)
see http://en.wikipedia.org/wiki/Date_format_by_country
This will try all culture:
public static bool TryParseAnyDate(string dateValue, out DateTime result)
{
result = DateTime.MinValue;
foreach (CultureInfo cultureInfo in CultureInfo.GetCultures(CultureTypes.AllCultures))
{
if (DateTime.TryParse(dateValue, cultureInfo, DateTimeStyles.None, out result))
{
return true;
}
}
return false;
}
I have a xml which can return a time in the format (7/23/2013 4:00pm) my question is: How can I explain to DateTime.ParseExact that I'm in the "am" or in the "pm"? I have this piece of code, but it returns me an exception (String can not be parsed)
I alredy placed an example string (7/23/2013 4:00pm) in which I replace "pm" by the empty chain "".
string pattern = "MM/dd/yyyy H:mm 'UTC' zzz";
DateTime time = DateTime.ParseExact(sb.ToString(), pattern, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal |
DateTimeStyles.AdjustToUniversal);
Thank you very much :)
You can pass an array to cover various formats. I use the following for various time inputs.
var formats = new[]
{
"M/dd/yyyy hh:mm tt",
"M/dd/yyyy hh:mmtt",
"M/dd/yyyy h:mm tt",
"M/dd/yyyy h:mmtt",
"M/dd/yyyy hhtt",
"M/dd/yyyy htt",
"M/dd/yyyy h tt",
"M/dd/yyyy hh tt"
};
var date = "7/23/2013 4:00pm";
DateTime time = DateTime.ParseExact(date, formats, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal |
DateTimeStyles.AdjustToUniversal);
H in your pattern expects the time in a 24 style. You need tt (as outlined in the previous answer) AND you must a small h in your pattern:
string pattern = "MM/dd/yyyy h:mm 'UTC' tt";
You need the tt format:
string pattern = "MM/dd/yyyy h:mm 'UTC' tt";
DateTime time = DateTime.ParseExact(sb.ToString(), pattern, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal |
DateTimeStyles.AdjustToUniversal);
DateTime dtEndTime = DateTime.ParseExact(
appToDate,
timeFormats,
null,
System.Globalization.DateTimeStyles.None);
appToDate = 21-02-2013 12:30 AM
string[] timeFormats = {
"dd-MM-yyyy H:m tt",
"dd-MM-yyyy H:mm tt",
"dd-MM-yyyy HH:m tt",
"dd-MM-yyyy HH:mm tt"
};
String was not recognized as a valid DateTime.
I suspect the problem is your use of H combined with tt. H and HH indicate an hour in the range 0-23, where 12 is noon, and therefore PM.
I suspect you want h and hh instead of H... although you shouldn't need every combination of h/H/m/mm. (Do you really expect to see "1:5 PM"?) I suspect just "dd-MM-yyyy H:mm tt" should cover you.