i have a string date in the following format
Thu Jan 5 19:58:58 2012
I need to parse this string to System.DateTime TimeReceived variable using DateTime.Parse() method.
Any one knows how to parse this string?
You could use the TryParseExact method which allows you to specify a format:
var str = "Thu Jan 5 19:58:58 2012";
DateTime date;
if (DateTime.TryParseExact(str, "ddd MMM d HH:mm:ss yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
// the date was successfully parsed, you could use the date variable here
Console.WriteLine("{0:HH:mm:ss dd/MMM/yy}", date);
}
if you look at the ParseExact function, about halfway there's
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
so if you'd switch those around to match what you want, you'll end up with
CultureInfo provider = CultureInfo.InvariantCulture;
// Parse date and time with custom specifier.
dateString = "Thu 5 Jan 19:58:58 2012";
format = "ddd MMM dd hh:mm:ss yyyy";
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);
}
var reformatted = input.Substring(4, 17) + input.Substring(22);
return DateTime.Parse(reformatted);
That should work fine.
Related
I am trying to parse Date/Time formats in HTTP/1.1 headers as specified in RFC2616
How do I parse an ANSI C timestamp in C#?
The closest I get is:
string dateFormat = "ddd MMM d HH':'mm':'ss yyyy";
DateTime time = DateTime.ParseExact("Mon Jan 2 15:04:05 2006", dateFormat, CultureInfo.InvariantCulture);
The problem lies in "d" which does not accept a leading space in case it is a single digit date. And "dd" requires a leading 0 instead.
Is there any easy way around, or maybe a library that already handles the three allowed date/time formats in HTTP/1.1?
How about using DateTime.TryParseExact overload that takes string[] as a format parameter with AllowInnerWhite style?
string s = "Sun, 06 Nov 1994 08:49:37 GMT";
DateTime dt;
var formats = new[]
{
"ddd, dd MMM yyyy HH:mm:ss 'GMT'",
"dddd, dd-MMM-yy HH:mm:ss 'GMT'",
"ddd MMM d HH:mm:ss yyyy"
};
if(DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture,
DateTimeStyles.AllowInnerWhite, out dt))
{
//
}
My problem is I have to parse a date in the format
Tue Oct 8 05:45 GMT
but what I always get using DateTime.parse() is:
system.formatexception the datetime represented by the string is not supported in calendar system.globalization.gregoriancalendar
how can this issue can be resolved?
Try this:
string format = "ddd MMM d hh:mm 'GMT'";
dateString = "Tue Oct 8 05:45 GMT";
CultureInfo provider = CultureInfo.InvariantCulture;
try
{
result = DateTime.ParseExact(dateString, format, provider);
}
catch (FormatException)
{
// Date does not conform to format defined
}
If the need for a try-catch causes you heartburn, then you can use TryParseExact(), like this:
string format = "ddd MMM d hh:mm 'GMT'";
dateString = "Tue Oct 8 05:45 GMT";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dateValue;
if (DateTime.TryParseExact(dateString, format, provider, DateTimeStyles.None,
out dateValue))
{
// Date conforms to format defined and result is in dateValue variable
}
else
{
// Date does not conform to format defined
}
This question already has answers here:
C# to Convert String to DateTime
(6 answers)
Closed 9 years ago.
I am extracting the data from an api and I am getting this value "Fri Aug 16 21:06:52 +0000 2013" I would like to know how I would be able to change this string value to type Date time
Use DateTime.ParseExact or (if the input may be invalid) DateTime.TryParseExact:
string input = "Aug 16 21:06:52 +0000 2013";
DateTime output;
if (DateTime.TryParseExact(input, "MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out output))
{
// date was parsable, here is it:
Console.WriteLine(output.ToLongDateString());
}
Custom Date and Time Format Strings, especially the "zzz" Custom Format Specifier
You can use DateTime.ParseExact
DateTime.ParseExact("Aug 16 21:06:52 +0000 2013", "MMM dd HH:mm:ss +ffff yyyy",
System.Globalization.CultureInfo.InvariantCulture);
You should read DateTime custom formats.
this should solve your problem thougf it
DateTime result = DateTime.ParseExact("Aug 16 21:06:52 +0000 2013", "MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture);
or to do it more appropriately and avoid exceptions. Do it like this
//zzz is Hours and minutes offset from UTC
string[] formats = { "MMM dd HH:mm:ss zzz yyyy" };
DateTime result;
string date = "Aug 16 21:06:52 +0000 2013";
if (DateTime.TryParseExact(date, formats, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
{
// i prefer this method though
}
Parsing string to datetime:
http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
DateTime.TryParse() returns true or false for success / fail.
http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
DateTime.Parse() throws an exception on failure.
There are a few ways...
DateTime.TryParse
DateTime dt;
if (DateTime.TryParse("Aug 16 21:06:52 +0000 2013", out dt))
{
//parsing was successfull
}
This won't throw an exception if the parse fails.
Then there is DateTime.Parse:
DateTime dt = DateTime.Parse("Aug 16 21:06:52 +0000 2013");
Unlike TryParse, this will throw an exception if parsing fails.
And there is also, Convert.ToDateTime:
DateTime dt = Convert.ToDateTime("Aug 16 21:06:52 +0000 2013", culture);
This also throws an error if the conversion fails.
Edited after you updated your question.
If you want it converted to your local time zone, use:
var dateTime = DateTime.ParseExact("Fri Aug 16 21:06:52 +0000 2013",
"ddd MMM dd HH:mm:ss zzz yyyy",
CultureInfo.InvariantCulture);
Otherwise, use:
var dateTime = DateTime.ParseExact("Fri Aug 16 21:06:52 +0000 2013",
"ddd MMM dd HH:mm:ss zzz yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal);
If the +0000 is always like that in the input, and you want to disregard that completely, use:
var dateTime = DateTime.ParseExact("Fri Aug 16 21:06:52 +0000 2013",
"ddd MMM dd HH:mm:ss +0000 yyyy",
CultureInfo.InvariantCulture);
I have a short program which converts a string to both date and time format from a simple string.
However it seems that the String is not recorgnizable for the system to be converted into date time format due to the sequence of the string. The String that should be converted is an example like : "Thu Dec 9 05:12:42 2010"
The method of Convert.ToDateTime have been used but does not work.
May someone please advise on the codes? Thanks!
String re = "Thu Dec 9 05:12:42 2010";
DateTime time = Convert.ToDateTime(re);
Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
Take a look at DateTime.TryParseExact
DateTime time;
if (DateTime.TryParseExact(re,
"ddd MMM d hh:mm:ss yyyy", CultureInfo.CurrentCulture,
DateTimeStyles.None, out time)) {
Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
} else {
Console.WriteLine("'{0}' is not in an acceptable format.", re);
}
It is often necessary to give it a hint about the specific pattern that you expect:
Edit: the double-space is a pain, as d doesn't handle that;
DateTime time = DateTime.ParseExact(re.Replace(" "," "),
"ddd MMM d hh:mm:ss yyyy", CultureInfo.CurrentCulture);
Take a look at DateTime.Parse
Try this
DateTime time = Convert.ToDateTime("2010, 9, 12, 05, 12, 42");
Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
Not sure if the string input should have the double space but you could pull that out and use geoff's answer.
re = Regex.Replace(re, #"\s+", " ");
Other option is to adjust his match string accordingly.
DateTime time = DateTime.ParseExact(re, "ddd MMM d HH:mm:ss yyyy", CultureInfo.CurrentCulture);
I have a program which converts a irregular date and time string into a system DateTime.
However as the system does not recognize irregular strings, the method .ParseExact, toDateTime and TryParse has not worked.
There are only 2 types of date time strings that the program needs to convert:
Thu Dec 9 05:12:42 2010
Mon Dec 13 06:45:58 2010
Please note that the single date has a double spacing which I have used the .replace method to convert the single date to Thu Dec 09 05:12:42 2010.
May someone please advise on the codes? Thanks!
The codes:
String rb = re.Replace(" ", " 0");
DateTime time = DateTime.ParseExact(rb, "ddd MMM dd hh:mm:ss yyyy", CultureInfo.CurrentCulture);
Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
I would really avoid regex and use what's already built-in .NET (TryParseExact method and date formats):
DateTime result;
string dateToParse = "Thu Dec 9 05:12:42 2010";
string format = "ddd MMM d HH:mm:ss yyyy";
if (DateTime.TryParseExact(
dateToParse,
format,
CultureInfo.InvariantCulture,
DateTimeStyles.AllowWhiteSpaces,
out result)
)
{
// The date was successfully parsed => use the result here
}
You should capture the parts of your datetime into capture groups in the Match Object, then reconstitute them any way you want.
You can use this Regex statement with named groups to make it easier
((?<day>)\w{3})\s+((?<month>)\w{3})\s+((?<date>)\d)\s((?<time>)[0-9:]+)\s+((?<year>)\d{4})
This is sample code which you can try:
var str = "Thu Dec 9 06:45:58 2010";
if (str.IndexOf(" ") > -1)
{
str = str.Replace(" ", " ");
DateTime time = DateTime.ParseExact(str, "ddd MMM d hh:mm:ss yyyy", null);
}
else
{
DateTime time = DateTime.ParseExact(str, "ddd MMM dd hh:mm:ss yyyy", null);
}