Converting string to DateTime [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Date time format from string?
Does anyone know how I could convert the following string to a DateTime value in C# ?
"Thu Nov 15 2012 00:00:00 GMT+0300 (E. Africa Standard Time)"

If you only have strings ending with "GMT+0300 (E. Africa Standard Time)", you can try:
string dateString = "Thu Nov 15 2012 00:00:00 GMT+0300 (E. Africa Standard Time)";
DateTime date = DateTime.ParseExact(dateString, "ddd MMM dd yyyy HH:mm:ss 'GMT+0300 (E. Africa Standard Time)'", System.Globalization.CultureInfo.InvariantCulture);
The meanings of the specifiers are as follows:
"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" The hour, using a 24-hour clock from 00 to 23.
"mm" The minute, from 00 through 59.
"ss" The second, from 00 through 59.
":" The time separator.
"string", 'string' Literal string delimiter.
You can find out more about different format specifiers in the MSDN article named Custom Date and Time Format Strings
Moreover, if you want to parse "GMT+0300 (E. Africa Standard Time)" part too, I think you should implement a way to parse them yourself. I don't think there's a specifier for that.

First of all, you should Africa Standart Time culture info use for yours';
CultureInfo( "af-ZA", false );
But your string is really complex for converting to DateTime. For me it looks imposible to convert to DateTime perfectly. But we can some rehabilitation in your string. For example, if your string was like this; "11/15/2012 00:00:00" you can convert it like this;
using System;
using System.Globalization;
namespace Programs
{
public class Program
{
public static void Main(string[] args)
{
string str = "11/15/2012 00:00:00";
DateTime dt = DateTime.ParseExact(str, "MM/dd/yyyy hh:mm:ss", new CultureInfo("af-ZA"));
Console.WriteLine(dt.ToString());
}
}
}
Custom Date and Time Format Strings
DateTime.ParseExact Method

Try this:
DateTime date = DateTime.Parse(yourDateTimeString);

There is no way to handle (E. Africa Standard Time).
Assuming that UTC=GMT you can also get the time zone part, just remove not important parts of your string
string t = Regex.Replace("Thu Nov 15 2012 00:00:00 GMT+0300 (E. Africa Standard Time)", "([(].+?[)])", "");
t= t.Replace("GMT", "").Trim();
DateTime a = DateTime.ParseExact(t, "ddd MMM dd yyyy HH:mm:ss zzzz", System.Globalization.CultureInfo.InvariantCulture);

Related

String was not recognized as a valid DateTime while converting from Arab Standard Time to datetime

I want to convert String into DateTime. Everything is correct but don't know why I am getting this error;
String was not recognized as a valid DateTime
string dtf = hdnFromDate.Value;
(While debugging I can see dtf value is Sun Dec 13 2020 00:00:00 GMT+0300 (Arab Standard Time)) and I am trying to convert into DateTime But no success
I am converting in this way
DateTime date = DateTime.ParseExact(dtf, "dd/MM/yyyy", null);
I also try like this
DateTime dt= DateTime.ParseExact(dtf,
"ddd MMM dd yyyy HH:mm:ss 'GMT'K '(Arab Standard Time)'",
CultureInfo.InvariantCulture);
Where I am doing wrong?
Reference to DateTime.ParseExact Method
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
So your datetime string should like this otherwise you will get exception
Mon Dec 14 2020 14:42:46 GMT+08:00 (Arab Standard Time)
or
Mon Dec 14 2020 14:42:46 GMT+0800 (Arab Standard Time)
You can try this to get what kind of string you need
Console.WriteLine(
DateTime.Now.ToString("ddd MMM dd yyyy HH: mm:ss 'GMT'K '(Arab Standard Time)'",
CultureInfo.InvariantCulture)
);
If your string have whitespace li
Mon Dec 14 2020 14: 42:46 GMT+08:00 (Arab Standard Time)
Yoo can try
Console.WriteLine(
DateTime.Now.ToString("ddd MMM dd yyyy HH: mm:ss 'GMT'K '(Arab Standard Time)'",
CultureInfo.InvariantCulture,
DateTimeStyles.AllowWhiteSpaces)
);

Parse string date (EEST included) but it fails

I am trying to parse a string into a DateTime, but it fails and shows an exception. The code is provided below:
static void Main(string[] args)
{
string dt = "Wed Sep 05 00:00:00 EEST 2012";
string Fm = "EEE MMM dd HH:mm:ss zzz yyyy";
DateTime dateTime;
dateTime = DateTime.ParseExact(dt, Fm, CultureInfo.InvariantCulture);
Console.WriteLine(dateTime.Date);
}
This is the exception:
Unhandled Exception: System.FormatException: String was not recognized as a valid DateTime.
at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)
at DateParser.Program.Main(String[] args) in C:\Users\AhmedSaeed\source\repos\DateParser\DateParser\Program.cs:line 17
string dt = "Wed Sep 05 00:00:00 EEST 2012";
Although a real timezone, "EEST" does not match the zzz format (in length) and this may be an issue.
Additionally, as apomene said, EEE is not a valid format string.
DateTime structure does not keep time zone information. It just have date and time values which is based a long called Ticks. That's why there is no custom date and time format string that matches that abbreviation. The zzz format specifier is for the signed offset of the local operating system's time zone from UTC and it is not meaninful to use it with DateTime parsing as stated on the documentation.
If you wanna parse an abbreviation in your string, you have to escape it as a string literal. Other than this, there is no way to parse it. On the other hand, timezone abbreviations are not even unique. For example, CST can mean Central Standard Time, China Standard Time or Cuba Standard Time.
Also there is no EEE custom date format specifier. Abbreviated day names matches with ddd format specifier instead.
string dt = "Wed Sep 05 00:00:00 EEST 2012";
string Fm = "ddd MMM dd HH:mm:ss 'EEST' yyyy";
DateTime dateTime = DateTime.ParseExact(dt, Fm, CultureInfo.InvariantCulture);
Console.WriteLine(dateTime.Date);
Here a demonstration.

Having problems with a datetime string

I have this method which shall return the day of the week (Wed):
protected string GetDayOfWeek(string dateTimeString)
{
DateTime result = DateTime.Parse(dateTimeString);
string dayOfWeek = Enum.GetName(typeof(DayOfWeek), result.DayOfWeek);
return dayOfWeek;
}
I have a breakpoint on the line DateTime result to check the incoming string which gives:
"Wed, 12 Mar 2014 00:00:00 GMT"
The above method is giving me error:
"FormatException not handled by the user code" String not recognised
as a valid dateTime.
What am I doing wrong? I cannot pick it up.
DateTime.Parse(string) uses the conventions of the current culture. So my guess is that "Wed, 12 Mar 2014 00:00:00 GMT" is not a valid date in your current culture.
You could try:
DateTime.Parse(dateTimeString, System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat)
That should tell the parser to be culture independent.
You can use:
DateTime.Now.DayOfWeek;
And compare with DayOfWeekclass.
Try using the method DateTime.ParseExact and provide an exact format string for your input. In your case the call shall look like:
DateTime myDate = DateTime.ParseExact("Wed, 12 Mar 2014 00:00:00 GMT", "ddd, dd MMM yyyy HH:mm:ss 'GMT'K", System.Globalization.CultureInfo.InvariantCulture);
There's two things going on here:
Parse a string into a DateTime
Get the DayOfWeek from the provided DateTime
As Tor-Erik suggests you can use DateTime.Parse with the invariant culture to get a DateTime.
DateTime.Parse(
dateTimeString,
System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat)
Then as Hevilávio Soares suggests you should use the built in functions of the DateTime object to obtain the Day of the week.
DateTime.Now.DayOfWeek;
It's better to separate the concerns and to reuse existing functionality than to write your own.

How can I convert this string to date?

Im making a post from a view and getting it in a actionresult as a string.
The value I get is:
Tue Feb 18 2014 00:00:00 GMT-0300 (Hora oficial do Brasil)
Using DateTime.Parse throws an exception:
String was not recognized as a valid DateTime.
What makes this string invalid, and how can I successfully convert it to a DateTime?
DateTime.Parse throws exception for this string because it does not have a standart date/time format.
If your GMT-0300 (Hora oficial do Brasil) is stable in your string, you can use;
var s = "Tue Feb 18 2014 00:00:00 GMT-0300 (Hora oficial do Brasil)";
var date = DateTime.ParseExact(s,
"ddd MMM dd yyyy HH:mm:ss 'GMT'K '(Hora oficial do Brasil)'",
CultureInfo.InvariantCulture);
Console.WriteLine(date);
Output will be;
2/18/2014 12:00:00 AM
Here is a demonstration.
I don't think there is a way to parse your (Hora oficial do Brasil) part except using string delimiter.
Take a look at;
The "K" Custom Format Specifier
I don't know why K specifier doesn't work on Ideone actually. I have to put -0300 part also as a string delimiter for generating example. It can be an issue with DateTimeKind enumeration but I'm not sure..
The string is invalid because of the 'GMT' and the '(Hora oficial do Brasil)' parts.
Simply put: the parser is unable to determine what is part of a date time and what is not.
By using format strings you will be able to parse the string into the DateTime format.
see: MSDN: Custom Date and Time Format Strings
in your case this format string will work: "ddd MMM dd yyyy hh:mm:ss 'GMT'K '(Hora oficial do Brasil)'".
You can use it like this:
string input = "Tue Feb 18 2014 00:00:00 GMT-0300 (Hora official do Brasil)";
string[] format = { "ddd MMM dd yyyy hh:mm:ss 'GMT'K '(Hora official do Brasil)'" };
DateTime date;
if (DateTime.TryParseExact(input, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
//Yepee the input was parsed correct
}
else
{
//system was unable to parse the string
}
Or like this if error handling is not nessesary:
string input = "Tue Feb 18 2014 00:00:00 GMT-0300 (Hora official do Brasil)";
string format = "ddd MMM dd yyyy hh:mm:ss 'GMT'K '(Hora official do Brasil)'";
DateTime date = DateTime.ParseExact(input, format, CultureInfo.InvariantCulture);

JSON date from tweeter to C# format

How to format a JSON date obtained from twitter to a C# DateTime ?
Here is the format of the date I receive :
"Tue, 19 Feb 2013 13:06:17 +0000"
Can I do it with JSON.NET ?
Solved with use of DateTime.ParseExact
-> http://blog.kevinyu.org/2012/07/handling-json-in-net.html
Link Update: the linked blog post is offline. It cached copy can still be referenced via the Way Back Machine Internet Archive.
The common .NET code copied from the blog post is:
public const string Const_TwitterDateTemplate = "ddd MMM dd HH:mm:ss +ffff yyyy";
DateTime createdAt = DateTime.ParseExact((string)jo["created_at"],
Const_TwitterDateTemplate, new System.Globalization.CultureInfo("en-US"));
where
variable jo is a JSON object representing the created_at date property, but effectively the Twitter date string goes into this parameter
Part of code from flow's answer.
public const string Const_TwitterDateTemplate = "ddd MMM dd HH:mm:ss +ffff yyyy";
DateTime createdAt = DateTime.ParseExact((string)jo["created_at"], Const_TwitterDateTemplate, new System.Globalization.CultureInfo("en-US"));
The answers above that use the ffff format specifier seem to return the correct result, but technically this is wrong. ffff is the format specifier for ten thousandths of a second, and the +0000 in a Twitter date indicates the hours and minutes offset from UTC. See the format below:
string twitterTime = "Wed Feb 22 15:49:01 +0000 2017";
string twitterTimeformat = "ddd MMM dd HH:mm:ss zzz yyyy";
DateTime dateTime = DateTime.ParseExact(twitterTime, twitterTimeformat,
CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
Console.WriteLine(dateTime);
Result: 2/22/2017 3:49:01 PM
You can edit the DateTimeStyles enumeration to return the local time instead of UTC if desired.
Custom Date and Time Format Strings
DateTimeStyles Enumeration
It's DateTimeOffset not DateTime. Following should work.
DateTimeOffset parsed = DateTimeOffset.Parse("Tue, 19 Feb 2013 13:06:17 +0000");
I needed a PowerShell variant of these answers and the following worked for me.
PS> $Created_At = 'Fri Jun 05 18:15:48 +0000 2020'
PS> [datetime]::ParseExact($Created_At,'ddd MMM dd HH:mm:ss zzz yyyy',(Get-Culture))
Friday, June 5, 2020 1:15:48 PM

Categories

Resources