C# How to convert String into Time and Date format? - c#

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);

Related

DateTime Parse ANSI C timestamp

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))
{
//
}

How to parse a string to DateTime

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.

C# DateTime.ParseExact throwing format exception

I'm developing an .NET4 webapplication using MVC3.
Let's say i'm getting the following DateTime as string from an XML-feed. The xml feed is being read by my application and i'm looping through all it's descendants. The DateTime i'm receiving is begin returned in the following format (as string);
var myDateTime = "Sun Dec 19 11:45:45 +0000 2010"
I'm using the piece of code below to try and parse the DateTime string i mentioned above to a valid DateTime format (preferably dutch)
var CorrectDateTime = DateTime.ParseExact(myDateTime , "dd MMM yyyy HH:mm:ss", CultureInfo.InvariantCulture);
When trying to execute this code i'm facing an formatexception. Somebody has got any ideas?
--UPDATE--
This is what i've got after various answers. Still throwing the same exception though.
var correctedDateTime = DateTime.ParseExact(latestTweetTime, "ddd MMM HH:mm:ss K yyyy", CultureInfo.InvariantCulture);
string display = correctedDateTime.ToString("dd MMM yyyy HH:mm:ss");
Try changing your parsing format to this:
"ddd MMM HH:mm:ss K yyyy"
If you wish to reformat the DateTimethen specify that format string when you call DateTime.ToString on your parsed DateTime:
string display = CorrectedDateTime.ToString("dd MMM yyyy HH:mm:ss");
If you're trying to read this:
"Sun Dec 19 11:45:45 +0000 2010"
You need an additional "d" or "dd" like so:
"ddd MMM d HH:mm:ss K yyyy"
or
"ddd MMM dd HH:mm:ss K yyyy"
depending on whether the input zero-prefixed.
You need each piece of the input string to be accounted for, here is a summary of the different components from MSDN: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
ddd = Three letter Day of week
MMM = Three letter month
dd = Two digit day of month 01-31 (use "d" for 1-31)
HH = Hours using 24-hour clock. 00-24 (use "H" for 0-24)
mm = Minutes. 00-59
ss = Seconds. 00-59
K = Time zone information
yyyy = 4-digit year
According to the date you've specified (assuming the time is in 24 hour) your input format string should be:
ddd MMM d H:mm:ss K yyyy.
Sun Dec 19 11:45:45 +0000 2010
So:
var correctedDateTime = DateTime.ParseExact(myDateTime, "ddd MMM d H:mm:ss K yyyy", CultureInfo.InvariantCulture);
string display = correctedDateTime.ToString("dd MMM yyyy HH:mm:ss");
A couple of things to note, the extra single d to capture the date and I would use a single H to allow for '01' and '1'. See http://msdn.microsoft.com/en-us/library/az4se3k1(v=VS.100).aspx for the full format details.

C# How to convert irregular date and time String into DateTime?

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);
}

How to parse DateTime in this format? "Sun May 23 22:00:00 UTC+0300 2010"

This is a quick one, i wanna parse a date that comes in this format "Sun May 23 22:00:00 UTC+0300 2010"
Is this a valid UTC DateTime? And how to parse it? I tried :
DateTime newStartTime = DateTime.ParseExact(hdnNewStartTime.Value, "ddd MM dd HH:mm:ss UTC+0300 yyyy", CultureInfo.CurrentCulture);
However, this didn't work, any help appreciated!
DateTime dt = DateTime.ParseExact(s,"ddd MMM dd HH:mm:ss UTCzzzz yyyy", System.Globalization.CultureInfo.InvariantCulture);
Its not a standard format, but you can still parse it.
string format = "ddd mmm dd HH:mm:ss zzzzz yyyy";
string temp = "Sun May 23 22:00:00 UTC+0300 2010";
DateTime time = DateTime.ParseExact(temp, format, CultureInfo.InvariantCulture);
This isn't in a standard .NET format, so you'll probably have to parse it by hand. The UTC+0300 bit indicates the timezone, everything else is part of the date and time.
I tried the solution presented by #johncatfish and it does what I expect. I would presume that you actually want to keep the timezone information.
[Test()]
public void TestCaseWorks ()
{
string format = "ddd MMM dd HH:mm:ss UTCzzzzz yyyy";
string temp = "Sun May 23 22:00:00 UTC+0300 2010";
DateTime time = DateTime.ParseExact(temp, format, CultureInfo.InvariantCulture);
Assert.AreEqual(DayOfWeek.Sunday, time.DayOfWeek);
Assert.AreEqual(5, time.Month);
Assert.AreEqual(23, time.Day);
Assert.AreEqual(0, time.Minute);
Assert.AreEqual(0, time.Second);
Assert.AreEqual(2010, time.Year);
// Below is the only actually useful assert -- making sure the
// timezone was parsed correctly.
// In my case, I am GMT-0700, the target time is GMT+0300 so
// 22 + (-7 - +3) = 12 is the expected answer. It is an exercise
// for the reader to make a robust test that will work in any
// timezone ;).
Assert.AreEqual(12, time.Hour);
}
Sorry for my previous answer which was quite simplistic.
Replace MM by MMM in your date format and it should be fine.
From the example given, it isn't possible to tell if the month should be in the 3 letter form (Jan, Feb, May etc.) or in the full form (January, February, May etc.).
If it should be in the short form, use:
ddd MMM dd HH:mm:ss UTCzzz yyyy
If it should be in the long form, use:
ddd MMMM dd HH:mm:ss UTCzzz yyyy
Details of the formatting specifiers available can be found at http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Categories