Correct format for DateTime.ParseExact - c#

I have the below string which I need to parse to a DateTime:
Thu Aug 14 2014 00:00:00 GMT 0100 (GMT Summer Time)
I am unsure what format to supply to my DateTime.ParseExact to achieve this. The nearest I could find in standard date/time format string was Full date/time pattern (long time) as below but this does not work
DateTime.ParseExact("Thu Aug 14 2014 00:00:00 GMT 0100 (GMT Summer Time)", "F", CultureInfo.InvariantCulture); // FormatException
Any ideas?

If the offset is not important, I suggest you just truncate the string after the time.
It looks like the format should allow that by finding the first space after position 16 (the start of the time in your example; part way through the time if the day number is shorter):
int endOfTime = text.IndexOf(' ', 16);
if (endOfTime == -1)
{
throw new FormatException("Unexpected date/time format");
}
text = text.Substring(0, endOfTime);
DateTime dateTime = DateTime.ParseExact(text, "ddd MMM d yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
(I'm assuming the month and day names are always in English.)

If you are certain it will always be GMT summer time, couldnĀ“t you use this:
var str = "Mon Jan 05 1987 07:45:30 GMT+0000 (GMT Summer Time)";
var f = "ddd MMM dd yyyy hh:mm:ss 'GMT'K' (GMT Summer Time)'";
var dateTime = DateTime.ParseExact(str, f, CultureInfo.InvariantCulture);
Or if summer/winter can change but always GMT, regardless of offset.
var str = "Mon Jan 05 1987 07:45:30 GMT+0000 (GMT Summer Time)".Split('(')[0].Trim();
var f = "ddd MMM dd yyyy hh:mm:ss 'GMT'K";
var dateTime = DateTime.ParseExact(str, f, CultureInfo.InvariantCulture);

Related

What's the format date Node js (new date()) on C# [duplicate]

I have date object in JavaScript which give me: "Wed Oct 01 2014 00:00:00 GMT+0200";
I try to parse it but I get an exception:
string Date = "Wed Oct 01 2014 00:00:00 GMT+0200";
DateTiem d = DateTime.ParseExact(Date,
"ddd MM dd yyyy HH:mm:ss GMTzzzzz",
CultureInfo.InvariantCulture);
MM format specifier is 2 digit month number from 01 to 12.
You need to use MMM format specifier instead for abbreviated name of month.
And for your +0200 part, you need to use K format specifier which has time zone information instead of zzzzz.
And you need to use single quotes for your GMT part as 'GMT' to specify it as literal string delimiter.
string s = "Wed Oct 01 2014 00:00:00 GMT+0200";
DateTime dt;
if(DateTime.TryParseExact(s, "ddd MMM dd yyyy HH:mm:ss 'GMT'K",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
Any z format specifier is not recommended with DateTime parsing. Because they represents signed offset of local time zone UTC value and this specifier doesn't effect DateTime.Kind property. And DateTime doesn't keep any offset value.
That's why this specifier fits with DateTimeOffset parsing instead.

Parse date and Convert W. Europe Standard Time to UTC

TL:DR: I have the following input string:
Thu Mar 09 2017 18:00:00 GMT+0100
And I am trying to convert it to a DateTime object using the format:
"ddd MMM dd yyyy HH:mm:ss"
This obviously doesn't work as I am ignoring the GMT+0100 part. How can I include this?
I don't manage to parse and convert following input to a correct UTC DateTime object:
input string selectedDate:
1,Thu Mar 09 2017 18:00:00 GMT+0100 (W. Europe Standard Time)
function:
var splittedValues = selectedDate.Split(',');
var selectDayOfWeek = (DayOfWeek)int.Parse(splittedValues[0]);
var selectedTime = DateTime.ParseExact(splittedValues[1].Substring(0, 24),
"ddd MMM d yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
DateTime today = new DateTime(DateTime.Today.Ticks, DateTimeKind.Unspecified);
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysUntilNextTargetDay = ((int)selectDayOfWeek - (int)today.DayOfWeek + 7) % 7;
DateTime nextTargetDay = today.AddDays(daysUntilNextTargetDay).AddHours(selectedTime.Hour).AddMinutes(selectedTime.Minute);
return nextTargetDay.ToUniversalTime();
results time portion is always 18:00:00
should be 17:00 as the input was actually GMT +01
Whats the issue here?
update:
as others pointed out there were mistakes so I updated my code to:
var splittedValues = selectedDate.Split(',');
var selectDayOfWeek = (DayOfWeek)int.Parse(splittedValues[0]);
var selectedTime = DateTime.ParseExact(splittedValues[1].Substring(0, 33),
"ddd MMM dd yyyy HH:mm:ss",
CultureInfo.InvariantCulture).ToUniversalTime();
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysUntilNextTargetDay = ((int)selectDayOfWeek - (int)DateTime.Today.DayOfWeek + 7) % 7;
DateTime nextTargetDay = DateTime.Today.AddDays(daysUntilNextTargetDay).AddHours(selectedTime.Hour).AddMinutes(selectedTime.Minute);
return nextTargetDay;
but now the parsing fails as the substring does not match "ddd MMM dd yyyy HH:mm:ss"
how does the GMT+0100 has to be included here?
Use TimeZoneInfo when converting between specific time zones:
TimeZoneInfo westInfo =
TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
DateTime westTime = DateTime.Parse("2012.12.04T08:35:00");
DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(westTime, westInfo);
To address your confusion:
DateTime.Parse as used here makes no assumptions about the timezone of the given value. IT stores it with a DateTimeKind of Unspecified.
TimeZoneInfo.ConvertTimeToUtc as used here expects an Unspecified datetime, reads it as if it is in the explicitly specified time zone, and converts it to UTC.
Changing your code to this (adding ToUniversalTime() before adding days) fixed it for me.
DateTime nextTargetDay = today.ToUniversalTime().AddDays(daysUntilNextTargetDay).AddHours(selectedTime.Hour).AddMinutes(selectedTime.Minute);
Then of course you can just return nextTargetDay; at the end.
Looking into MSDN I can spot an initial problem with your code. This is that you are using d where you should be using dd as the day is 09 not 9.
d: The day of the month, from 1 through 31.
dd: The day of the month, from 01 through 31.
Secondly, the reason the +1 is "ignored" is that you exclude it in the substring, i.e.
splittedValues[1].Substring(0, 24) == "Thu Mar 09 2017 18:00:00";
So essentially you need to include that part of the string with the correct format specifier (I'm not sure which one). Or interrogate it yourself and subtract one hour off of the result as needed.
Side note: The following code is weird (in my opinion, there may be a reason for it):
DateTime today = new DateTime(DateTime.Today.Ticks, DateTimeKind.Unspecified);
You can either use DateTime.Today or DateTime.Now.Date.
As mentioned in the answer by #calypso you can use the TimeZoneInfo class. Their answer goes over a general approach of how to use it. But for your particular example you can do (code is untested but looks like it should work):
var selectedTime = DateTime.ParseExact(splittedValues[1].Substring(0, 24), "ddd MMM dd yyyy HH:mm:ss", CultureInfo.InvariantCulture);
TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(splittedValues[1].Substring(splittedValues[1].IndexOf("(") + 1).TrimEnd(")"));
DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(selectedTime, timeZoneInfo);

How to parse string which contains GMT to DateTime?

How can I convert this string:
string aa ="Thu Jul 02 2015 00:00:00 GMT+0100 (GMT Standard Time)";
into a DateTime.
I tried to use the Convert.ToDateTime(aa); but didn't work
Thanks.
EDIT: error message - The string was not recognized as a valid DateTime
You can use DateTime.TryParseExact with the correct format string:
string dtString = "Thu Jul 02 2015 00:00:00 GMT+0100";
string format = "ddd MMM dd yyyy HH:mm:ss 'GMT'K";
DateTime date;
bool validFormat = DateTime.TryParseExact(dtString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
Console.Write(validFormat ? date.ToString() : "Not a valid format");
If the string contains (GMT Standard Time) at the end you could simply remove it first:
dtString = dtString.Replace("(GMT Standard Time)", "").Trim();
or use this format pattern:
string format = "ddd MMM dd yyyy HH:mm:ss 'GMT'K '(GMT Standard Time)'";
Further informations: https://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Using DateTime.Parse Method:
using System;
public class Example
{
public static void Main()
{
string[] dateStrings = {"2008-05-01T07:34:42-5:00",
"2008-05-01 7:34:42Z",
"Thu, 01 May 2008 07:34:42 GMT"};
foreach (string dateString in dateStrings)
{
DateTime convertedDate = DateTime.Parse(dateString);
Console.WriteLine("Converted {0} to {1} time {2}",
dateString,
convertedDate.Kind.ToString(),
convertedDate);
}
}
}
// These calls to the DateTime.Parse method display the following output:
// Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM
// Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM
// Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM
Since you have an UTC offset in your string, I would prefer to parse DateTimeOffset instead of DateTime. And there is no way to parse your GMT and (GMT Standard Time) parts without escape them.
Both DateTime and DateTimeOffset are timezone awareness by the way. DateTimeOffset little bit better than DateTime for this situation. It has UTC Offset but this doesn't guaranteed the timezone information because different timezones can have same offset value.
Even if they are, time zone abbreviations are not standardized. CST has several meanings for example.
string s = "Thu Jul 02 2015 00:00:00 GMT+01:00 (GMT Standard Time)";
DateTimeOffset dto;
if (DateTimeOffset.TryParseExact(s, "ddd MMM dd yyyy HH:mm:ss 'GMT'K '(GMT Standard Time)'",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dto))
{
Console.WriteLine(dto);
}
Now, you have a DateTimeOffset as {02.07.2015 00:00:00 +01:00}

How to format string to datetime?

I have devexpress dateedit object and I send selected date to controller from clientside but i cant convert my string date value to datetime value
When I try I get this error => string was not recognized as a valid DateTime
my string date value => Thu Aug 28 2014 00:00:00 GMT+0300 (Turkey Daylight Time)
Convert Code =>
DateTime startDate = DateTime.ParseExact(sDate, "ddd MMM d yyyy HH:mm:ss zzzz", CultureInfo.InvariantCulture);
How should I do format this string ?
You need to "escape" unrecognized symbols with single quote:
var sDate = "Thu Aug 28 2014 00:00:00 GMT+0300 (Turkey Daylight Time)";
var format = "ddd MMM dd yyyy HH:mm:ss 'GMT'zzzz '(Turkey Daylight Time)'";
DateTime startDate = DateTime.ParseExact(sDate, format, CultureInfo.InvariantCulture);
Console.WriteLine(startDate);
prints:
8/28/2014 12:00:00 AM
Works well with single d in third group, added one just for clarity.
Single or double quotes denote Literal string delimiter. You can read and check more examples at this msdn article on DateTime formats
First convert date string to date and then date to ISO and send it to server. That would work.
var date = new Date("Thu Aug 28 2014 00:00:00 GMT+0300")
var sDate = date.toISOString();
Try removing the unknown format with Regex first.
var sDate = #"Thu Aug 28 2014 00:00:00 GMT+0300 (Turkey Daylight Time)";
var sDateOnly = Regex.Replace(sDate, #"\s*(\(.*\))", m => string.Empty);
var f = #"ddd MMM d yyyy HH:mm:ss \G\M\Tzzzz";
DateTime startDate = DateTime.ParseExact(sDateOnly, f, CultureInfo.InvariantCulture);

string to date - in C# [ "Mon Jan 13 2014 00:00:00 GMT+0000 (GMT Standard Time)"]

I have a situation in which I am receiving date as a string in following format.
"Mon Jan 13 2014 00:00:00 GMT+0000 (GMT Standard Time)"
I need to convert it to following format in c# (Either date/string) for further processing
YYYY-MM-DD (2014-01-13)
Convert.ToDateTime(SelectedData)
Above code thorws following error:
'Convert.ToDateTime(SelectedData)' threw an exception
of type 'System.FormatException' System.DateTime {System.FormatException}
Any suggestions?
I can't change the format in which I am receiving the date
Best Regards.
You're going to need to use DateTime.ParseExact:
var date = DateTime.ParseExact(
"Mon Jan 13 2014 00:00:00 GMT+0000 (GMT Standard Time)",
"ddd MMM dd yyyy HH:mm:ss 'GMT'K '(GMT Standard Time)'",
CultureInfo.InvariantCulture);
after parsing the date you can then send it out your way:
date.ToString("yyyy-MM-dd");
Here's an Ideone to prove it.
Convert.ToDateTime uses standart date and time formats and this is not a standart DateTime format.
If your GMT+0000 (GMT Standard Time) is defult in your string, you can use DateTime.ParseExact instead like;
string s = "Mon Jan 13 2014 00:00:00 GMT+0000 (GMT Standard Time)";
var date = DateTime.ParseExact(s,
"ddd MMM dd yyyy HH:mm:ss 'GMT+0000 (GMT Standard Time)'",
CultureInfo.InvariantCulture);
Console.WriteLine(date.ToString("yyyy-MM-dd"));
Output will be;
2014-01-13
Here a demonstration.
For more information, take a loo at:
Custom Date and Time Format Strings
The "K" custom format specifier
string date = SelectedData.Substring(4, 11);
string s = DateTime.ParseExact(date, "MMM dd yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");

Categories