I have an MVC application.
At controller(from view) I am getting start date as string "Tue Jan 01 2008 00:00:00 GMT 0100 (Central Europe Standard Time)".
Could anybody please tell me how to convert this datetime to normal dd-mmy-yyyy hh:mm:ss at Controller level.
Thanks in advance....
You need to use the DateTime.ParseExact method and supply the correct format string so the code knows what each part of the input string represents.
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "ddd MMM dd yyyy hh:mm tt zzz";
result = DateTime.ParseExact(dateString, format, provider);
Double check the format strings against the documentation there are several subtle and not so subtle gotchas:
"h" represents the hour in 12 hour clock
"hh" represents the hour in 12 hour clock with leading zero
"HH" represents the hour in 24 hour clock with leading zero
"m" represents a minute from 0 to 59
"M" represents a month from 1 to 12
etc.
So you may find that you think your format string is OK for the examples you have, but then a new string will come along which won't parse. You'll have to examine it to see if you've got hours in 12 or 24 hour format, etc.
Though you will have to strip of the timezone name from the end of the string first as that won't be recognised by ParseExact.
Related
I'm trying to parse DateTime data from podcast XML.
Basically, it comprises http header format.
(Format-A) Fri, 28 Aug 2015 00:00:00 EST
But, sometimes it has the different format with 4 digit days and month like below.
(Format-B) Thur, 30 July 2015 00:00:00 EST
I don't know why the Podcast provides 2 different formats at the same time.
I thought I could simply parse this format as this website mentioned.
https://www.dotnetperls.com/datetime-parse
But it didn't work with just DateTime.Parse() method
So I wrote this code.
try
{
dtPubDate = DateTime.ParseExact(strhttpTime,
"ddd, dd MMM yyyy HH:mm:ss 'EST'",
CultureInfo.InvariantCulture.DateTimeFormat,
DateTimeStyles.AssumeUniversal);
}
catch (FormatException)
{
dtPubDate = DateTime.ParseExact(strhttpTime,
"dddd, dd MMMM yyyy HH:mm:ss 'EST'",
CultureInfo.InvariantCulture.DateTimeFormat,
DateTimeStyles.AssumeUniversal);
}
As I wrote this code, if the first format doesn't work, try the second one.
But it still got the exception with Format-B.
This URL is what am having the problem with.
http://www.thebreathingmusic.com/podcast/podcast.xml
As you can see, there are 2 different formats with pubDate tag.
What am I missing?
The format string dddd will match against the entire day name, e.g. "Thursday", not 4 characters.
From the docs:
The "dddd" custom format specifier (plus any number of additional "d" specifiers) represents the full name of the day of the week. The localized name of the day of the week is retrieved from the DateTimeFormatInfo.DayNames property of the current or specified culture.
You could just trim everything before the comma and parse that instead.
var tidyDate = strhttpTime.Split(',')[1].Trim();
dtPubDate = DateTime.ParseExact(
tidyDate,
"ddd, dd MMM yyyy HH:mm:ss 'EST'",
CultureInfo.InvariantCulture.DateTimeFormat,
DateTimeStyles.AssumeUniversal);
I am trying to set the DateTime format to 24 hours. Originally I have a string with a 12 hour representation. All solutions I have found are converting DateTime to string.
string dateString = "Mon 16 Jun 8:30 AM 2008"; // <-- Valid
string format = "dd/MM/yyyy HH:mm";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out dateTime))
{
DateTime dateIn24 = dateTime;// dateIn24 should be in 24 hour format
}
Is there anything we can do in web.config? Like the following:
<globalization fileEncoding="utf-8" requestEncoding="utf-8" responseEncoding="utf-8" culture="en-GB" uiCulture="en-GB"/>
i got the answer
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
if its en-US 12 hour format
by default it will be en-US based on system date time settings
The DateTime instance only contains the information, and the Hour property is an integer from 0 to 23, according to MSDN documentation:
Property Value
Type: System.Int32
The hour component, expressed as a value between 0 and 23.
https://msdn.microsoft.com/library/system.datetime.hour(v=vs.110).aspx
If you're talking about formatting it, then you need to convert it to a string, like mentioned in the comments.
As far as I know, the 24-hour format is neither not a matter of how the DateTime is parsed, nor saved, but rather of the formatting. Given that you enter the if-block (I have not been successful on parsing youre dateString in LinqPad) you can obtain a correctly formatted date string with
var dateStringWith24Hours = dateTime.ToString(dateString);
since the HH in your format string means that you'd like to format the hours as 24 hours.
How can I convert Tue, 01 Nov 2016 02:00 PM EET datetime string to DateTime in C#? What is a good practice to do it?
Use DateTime.TryParseExact with a format string that represents a generic datetime.
If you can have multiple formats then use the DateTime.TryParseExact overload that takes an array of formats.
You can find all the format strings here:
Custom Date and Time Format Strings
For example, "Tue" is represented by "ddd", "Nov" by "MMM" etc.
NOTE: The string formats are case sensitive so while "M" represents the month number, "m" represents the minute number. Getting them mixed up will cause the parse to fail.
By replacing timezone abbreviation with zone offset you can convert using DateTime.ParseExact
string date = "Tue, 01 Nov 2016 02:00 PM EET";
DateTime dt = DateTime.ParseExact(date.Replace("EET", "+2"), "ddd, dd MMM yyyy hh:mm tt z", CultureInfo.InvariantCulture);
and if you want more safer way by checking exception then you can using DateTime.TryParseExact method
Use DateTime.TryParseExact where the format string is built using this table.
Custom date and time formats does not recognize timezone abbrevations. You need to escape them as a string literal delimiter.
var dt = DateTime.ParseExact("Tue, 01 Nov 2016 02:00 PM EET",
"ddd, dd MMM yyyy hh:mm tt 'EET'",
CultureInfo.InvariantCulture);
dt.Dump();
This is a very strange date fromat I have never seen before coming back from some API in JSON.
"Tue Aug 04 2015 00:17:38 GMT+0000 (UTC)"
That is generating the following error:
System.FormatException: String was not recognized as a valid DateTime.
Which is understandable when using the following method to parse:
DateTime.Parse(x.process_date.Value)
Anyone dealt with complex date formats that may know how to parse that?
You can use the DateTime.ParseExact method (or DateTime.TryParseExact, to cleanly handle parsing failures) to accomplish this. These methods allow you to explicitly specify the format string.
Something like this could work:
var dateString = "Tue Aug 04 2015 00:17:38 GMT+0000 (UTC)";
var format = "ddd MMM dd yyyy HH:mm:ss GMT+0000 (UTC)";
var parsed = DateTime.ParseExact(
dateString,
format,
System.Globalization.CultureInfo.InvariantCulture);
Or, using TryParseExact:
DateTime parsed;
if (DateTime.TryParseExact(
dateString,
format,
System.Globalization.CultureInfo.InvariantCulture,
DateTimeStyles.None,
out parsed)
{
// parsing was successful
}
else
{
// parsing failed
}
Here's a breakdown of the format string used here:
ddd - The abbreviated name of the day of the week.
MMM - The abbreviated name of the month.
dd - The day of the month, from 01 through 31.
yyyy - The year as a four-digit number.
HH:mm:ss - The hour, using a 24-hour clock from 00 to 23; the minute, from 00 through 59; and the second, from 0 through 59 (delimited by : characters).
GMT+0000 (UTC) - just static text that the format string assumes will always be present. This is pretty brittle and could cause your parsing to fail if the API ever returns different text here. Consider truncating this text, or using NodaTime which offers great support for time zones.
You might need to tweak this format string slightly to your usage -- for example, it wasn't clear from your question whether or not you are using a 12-hour clock or a 24-hour clock.
For more information on how to build a format string, see Custom Date and Time Format Strings on MSDN.
Alternatively, you could eschew using System.DateTime in favor of NodaTime. I'm less familiar with NodaTime myself, but great documentation is available both here on StackOverflow and on NodaTime's site.
I'm trying to use DateTime.TryParseExact as below:
DateTime modifiedSinceDateTime;
var succeeded = DateTime.TryParseExact(modifiedSince, "yyyy-MM-ddThh:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out modifiedSinceDateTime);
but it fails with this DateTime value: 2013-06-06T22:41:20 which suggests my date time pattern is not right. I think the pattern doesn't support 24 hours timing format, only up to 12 hours
What should be the correct date pattern like?
Simple enough - change the hh to HH.
hh is for 12 hour clocks, HH for 24 hours, as can be seen in the documentation for Custom Date and Time Format Strings.