JSON date from tweeter to C# format - c#

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

Related

Convert string to datetime UTC

I have this string "Sun Aug 02 2015 00:15:47 GMT+0000 (UTC)"
I created this much of the datetime format "ddd MMM dd yyyy HH:mm:ss"
Now im not sure what to do with the ending part of that datetime string.
Im not sure if the string I have is a standard format for UTC that can be easily converted or if its a custom format.
Nonetheless, I want to turn that string datetime into a datetime object.
string str = "Sun Aug 02 2015 00:15:47 GMT+0000 (UTC)";
var dt = DateTime.ParseExact(str, "ddd MMM dd yyyy HH:mm:ss \"GMT\"zzzz \"(UTC)\"", CultureInfo.InvariantCulture);
I would consider one of these two approaches:
string str = "Sun Aug 02 2015 00:15:47 GMT+00:00 (UTC)";
str = str.Substring(0, str.IndexOf('(') - 1);
DateTime dt = DateTime.ParseExact(str, "ddd MMM dd yyyy HH:mm:ss 'GMT'K",
CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
or
string str = "Sun Aug 02 2015 00:15:47 GMT+00:00 (UTC)";
str = str.Substring(0, str.IndexOf('(') - 1);
DateTimeOffset dto = DateTimeOffset.ParseExact(str, "ddd MMM dd yyyy HH:mm:ss 'GMT'K",
CultureInfo.InvariantCulture);
In either example, we assume that the part in parenthesis is irrelevant. This may be important if your input can vary with different time zones.
In the first example, we assume that you want the output to always be a UTC based DateTime. The input offset could vary, but the output will always be adjusted to Coordinated Universal Time, and will have DateTimKind.Utc.
In the second example, we assume that you want the output to match exactly what was provided in the input. To do this, the output needs to be a DateTimeOffset type. Otherwise, you wouldn't be able to track offsets that didn't exactly match UTC or your own local time zone.
I prefer the second option. If you need a DateTime, you can always get one by calling the .DateTime, .UtcDateTime, or .LocalDateTime properties of the resulting DateTimeOffset.

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

DateTime format in c# .Net

I have a json, I parse the json and get a value in a var created_on like this:
var created_on = jsonr["created_at"];
The value is
created_on = Tue Feb 04 14:02:45 +0000 2014
i want to convert it to utc.
I followed quick links in stack but am not able to format accordingly.
Anyone who knows this?
You can use ParseExact to parse the string into a date:
DateTime.ParseExact(created_on,
"ddd MMM dd HH:mm:ss zz00 yyyy",
CultureInfo.InvariantCulture)
.ToUniversalTime();

Error : String was not recognized as a valid DateTime while converting to date format in c#

Here is the date time format i'm trying to format.I'm getting this date format from twitter apis
string date = "Thu Jul 18 17:39:53 +0000 2013"
i tried
Convert.ToDateTime(date).ToString("dd/MM/yyyy")
But it says String was not recognized as a valid DateTime.
This works:
DateTime.ParseExact(dtStr, "ddd MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture)
ParseExact and TryParseExact allows to use a custom format string. ddd is the abbreviated day name, MMM the abbreviated month name, dd the day number, HH hours in 24h clock format, mm minutes, ss seconds, zzzz the time-zone and yyyy the years.
I have used CultureInfo.InvariantCulture to specify that the current culture is not used but InvariantCulture which is similar to "en-US".
Demo
works but after getting date from your line of code i tried to do
date.ToString("dd/mm/yyyy") but get the string as 12-12-2013, no
slashes
/ is a replacement character for your current culture's date-separator which is obviously -. So also use CultureInfo.InvariantCulture to specify that the separator should be used without using your current culture:
string result = dateTime.ToString("dd/mm/yyyy", CultureInfo.InvariantCulture);
See: The "/" Custom Format Specifier
Try this
DateTime.ParseExact(YourDate, "ddd MMM dd HH:mm:ss KKKK yyyy", CultureInfo.InvariantCulture)
Its better to use Invariant culture than Current culture
You are trying to convert a non-standard format, so use this:
string dateStr = "Thu Jul 18 17:39:53 +0000 2013";
DateTime date = DateTime.ParseExact(dateStr, "ddd MMM dd h:mm:ss KKKK yyyy", System.Globalization.CultureInfo.InvariantCulture);
Or build the correct format for your input.
How about like;
string date = "Thu Jul 18 17:39:53 +0000 2013";
DateTime dt = DateTime.ParseExact(date, "ddd MMM dd HH:mm:ss KKKK yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(dt);
Output will be;
18.07.2013 20:39:53
K for time zone information in here.
Check out for more information;
Custom Date and Time Format Strings
Your date string needs to be this:
Thu Jul 18 2013 17:39:53 +0000
Whatever is producing your string needs to have the year value after the month and day and before the time, like above.
string date = "Thu Jul 18 2013 17:39:53 +0000";
var theDate = Convert.ToDateTime(date);
Note: This will produce a valid .NET DateTime object.
UPDATE:
If you cannot change the string produced, then use the ParseExact method with a custom format, like this:
string date = "Thu Jul 18 17:39:53 +0000 2013";
var theDate = DateTime.ParseExact(date, "ddd MMM dd H:mm:ss zzz yyyy", CultureInfo.InvariantCulture);
Try using DateTime.ParseExact.
string date = "Thu Jul 18 17:39:53 +0000 2013"
DateTime date = DateTime.ParseExact(date, "dd/MM/yyyy", null);
this.Text="22/11/2009";
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);

How do I parse a string into a DateTime, with a specific format?

I have a source where dates comes in this string form:
Sat Sep 22 13:15:03 2018
Is there an easy way I can parse that into a DateTime in C#? I've tried with DateTime.(Try)Parse, but it doesn't seem to recognize this specific format...
You should prefer DateTime.ParseExact and TryParseExact; these methods let you specify the expected format(s) in your program.
The DateTime.Parse and TryParse methods are dangerous because they accept the current date/time format configured on the machine where the code is running -- which the user can change from the default -- along with a couple of culture-neutral formats. In other words, the user can change settings in Control Panel and break Parse/TryParse.
This works:
DateTime dt = DateTime.ParseExact ("Sat Sep 22 13:15:03 2018", "ddd MMM d HH:mm:ss yyyy", null)
Try DateTime.ParseExact
This code takes your date string and applies a format to create a DateTime object.
CultureInfo provider = CultureInfo.InvariantCulture;
string dateString = "Sat Sep 22 13:12:03 2018";
string format = "ddd MMM dd HH':'mm':'ss yyyy";
DateTime result = DateTime.ParseExact(dateString, format, provider);
var str = "Sat Sep 22 13:15:03 2018";
var date = DateTime.ParseExact(str, "ddd MMM dd HH:mm:ss yyyy", CultureInfo.InvariantCulture);

Categories

Resources