DateTime.ParseExact Failing to convert to correct date - c#

I am using FullCalendar. Now there is a code where I get a Date/Time from FullCalendar API. This is called startDate and has a below format:
String. An ISO8601 string representation of the start date. It will
have a timezone offset similar to the calendar’s timeZone e.g.
2018-09-01T12:30:00-05:00. If selecting all-day cells, it won’t have a
time nor timezone part e.g. 2018-09-01.
Let us for this question, assume that startStr is 2020-11-15T23:00:00-08:00
I have an ASP.NET MVC backend, where I send this string using Javascript.
The server receives the correct string as above i.e. 2020-11-15T23:00:00-08:00
Now, there is a code where I parse this date to the DateTime object
DateTime sdt = DateTime.ParseExact(sstartStr, "yyyy'-'MM'-'dd'T'HH':'mm':'sszzz", CultureInfo.InvariantCulture)
But here, this date/time is parsed as 11/16/2020 12:30:00 PM.
(You can try parsing the said date using the above code, the output will be wrong as above.)
Am I missing something ?

Related

Convert JSON date to C# datetime variable

I want to convert my JSON formatted date to C# DateTime variable. Trying to convert it with Convert.ToDateTime
("2016-01-15T11:44:52-07:00")
is giving me this output
"1/16/2016 12:14:52 AM"
I am not able to find out whether it is a correct output or not because my input date is 15 Jan 2016 but in output it is 16 Jan 2016.
How can I convert a JSON date value to a C# date value?
Looks like your current timezone is UTC +05:30 right now and that's why Convert.ToDateTime method adds those value to the result and generates 1/16/2016 00:14:52 as a value.
Since your string has an offset part, I would parse it to DateTimeOffset instead of Datetime.
var dto = DateTimeOffset.Parse("2016-01-15T11:44:52-07:00");
This will generate {15.01.2016 11:44:52 -07:00} as a DateTimeOffset.
But since you said this is related with Json, this technology should have some methods to parse it as well. It would be better to use those methods but I'm not familiar with JSON.
You seem to have problems with the time zones. Try parsing with DateTimeStyles.RoundtripKind
using System.Globalization;
var s1 = "2016-01-15T11:44:52-07:00";
var date = DateTime.Parse(s1, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);

Parse date time c# with correct timezone and kind

I have a datetime in database which I read using SqlDataReader and then cast it to (DateTime). After the cast its Kind property is DateTimeKind.Unspecified.
Then I have another string which I read from some other source. Its format is like this 2016-01-20T22:20:29.055Z. I do DateTime.Parse("2016-01-20T22:20:29.055Z") and its Kind property is DateTimeKind.Local.
How do I properly parse the both date times for comparison? Do I need to use DateTimeOffsets? How should I parse them?
Thanks
Because SQLReader cannot reasonably infer a DateTimeKind, it leaves it as unspecified. You'll want to use DateTime.SpecifyKind to change the DateTimeKind on your output from the SQLReader to the appropriate value. This works ok if you are only dealing with UTC and one consistent local time zone; otherwise, you really should be using DateTimeOffset in both your code and the SQL Database.
The string "2016-01-20T22:20:29.055Z" is ISO 8601 compliant and is a UTC date; however, DateTime.Parse with only 1 argument can end up performing a conversion to local time. Per the documentation:
Generally, the Parse method returns a DateTime object whose Kind
property is DateTimeKind.Unspecified. However, the Parse method may
also perform time zone conversion and set the value of the Kind
property differently, depending on the values of the s and styles
parameters:
If s contains time zone information, the date and time is converted
to the time in the local time zone and the Kind is DateTimeKind.Local.
If s contains time zone information, and styles includes the
AdjustToUniversalflag, the date and time is converted to Coordinated
Universal Time (UTC) and the Kind is DateTimeKind.Utc.
If s contains the Z or GMT time zone designator, and styles includes
the RoundtripKind flag, the date and time are interpreted as UTC and
the Kind is DateTimeKind.Utc.
Also see UTC gotchas in .NET and SQL Server in Derek Fowler's blog for additional coverage on the topic.
In your second example, 2016-01-20T22:20:29.055Z has timezone information provided with it; the 'Z' at the end indicates that the timestamp is intended for Coordinated Universal Time (UTC). However, DateTime.Parse() will default its conversion using DateTimeKind.Local unless a specific timezone is specified. You can use DateTime.ParseExact to be more specific.
As to why the datetime values in your database are coming out as Unspecified, that's likely because they contain no timezone indication at all. Check to see if your database values specify timezone information, either by using 'Z' at the end or specifying an exact timezone, such as 2016-01-20T22:20:29.055-07:00 (UTC-7).
You can use something like this:
string format = "ddd dd MMM h:mm tt yyyy";
DateTime dateTime = DateTime.ParseExact(dateString, format,
CultureInfo.InvariantCulture);
In format variable, you can put the format you want, and pass it to ParseExact function.
Hope it helps.
You are missing the datetime context (offset) in your database. You should persist it either in a datetimeoffset column or in a datetime column but persisting utc datetimes.
And always better compare two utc datetimes.
I coded a quick C# console app that I pasted in below. This converts a UTC date and time to a string (format similar to the ISO 8601 format described in another post with some extra digits of precision), writes it to a file, reads it from the file (as a string) and then converts it back to a UTC date and time.
It then compares the two UTC Date Time objects, which are both of UTC kind, and they match.
class Program
{
// "2016-01-20T22:20:29.055Z" is ISO 8601 compliant and is a UTC date
const string dtf = "yyyy-MM-ddTHH:mm:ss.fffffffZ";
static void Main(string[] args)
{
string file = #"c:\temp\file.txt";
DateTime dt = DateTime.UtcNow;
using (var sw = new System.IO.StreamWriter(file))
{
sw.WriteLine(dt.ToString(dtf, System.Globalization.CultureInfo.InvariantCulture));
}
DateTime dtin;
using (var sr = new System.IO.StreamReader(file))
{
dtin = DateTime.ParseExact(sr.ReadLine(), dtf, System.Globalization.CultureInfo.InvariantCulture);
}
Console.WriteLine(dt.ToString(dtf) + "\r\n" + dtin.ToString(dtf) + "\r\nEquality:" + (dt == dtin));
Console.ReadLine();
}
}

Parse a UTC date string to date in C#

Simple question, I have this string:
string dateString = "7/12/2014 4:42:00 PM";
This is a date string and it's in the UTC timezone.
I need to convert it to a date, so I'm doing the following:
DateTimeOffset dateOffset;
DateTimeOffset.TryParse(dateString, out dateOffset);
DateTime date = dateOffset.UtcDateTime;
The problem:
When I'm parsing the string to date, the code is considering that the dateString is in the Local Timezone of the PC (+3 GMT), and not in the UTC timezone.
So I am getting the following the dateOffset = {7/12/2014 4:42:00 PM +03:00} and thus date = {7/12/2014 1:42:00 PM}
how can I tell him that the date string provided is in the UTC format and not in the local timezone format?
Thanks
how can I tell him that the date string provided is in the UTC format and not in the local timezone format?
Specify a DateTimeStyles value of AssumeUniversal in the call. That tells the parsing code what to do. For example:
// null here means the thread's current culture - adjust it accordingly.
if (DateTimeOffset.TryParse(dateString, null, DateTimeStyles.AssumeUniversal,
out dateOffset))
{
// Valid
}
You should always use the result of TryParse to tell whether or not it's successfully parsed.
If you know the format and the specific culture, I'd personally use DateTimeOffset.TryParseExact. (Well, to be honest I'd use my Noda Time project to start with, but that's a different matter.)
There is another overload of DateTimeOffset.TryParse
DateTimeOffset.TryParse Method (String, IFormatProvider, DateTimeStyles, DateTimeOffset)
which allows you specify DateTimeStyles. One of the DateTimeStyles is AssumeUniversal, which is what you're looking for:
If no time zone is specified in the parsed string, the string is
assumed to denote a UTC. This value cannot be used with AssumeLocal or
RoundtripKind.
Don't know how .Net API provides, but I guess you could probably use ISO8601 format to indicate a UTC timezone before parsing, i.e, first translate 7/12/2014 4:42:00 PM into something 2014-07-02T16:42:00Z, then use try parse using DateTimeOffset

.NET DateTime to BizTalk DateTime

I have date in this format "1999-05-31T13:20:00.000-05:00" I want to add some hours or days to it . BizTalk expects same datetime format how can i pass it as Datetime in that format ? No string . Date time with same format as source date.
You should be able to do something like this to get it into a DateTimeOffset object. After that you can call whatever methods you want on it.
DateTimeOffset dateTime = DateTimeOffset.Parse( "1999-05-31T13:20:00.000-05:00" );
To get the value back just use a formatting string.
dateTime.ToString( "O" ); //this should be the same format as you started with
Here are some other options http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
Here is a link to the DateTimeOffset structure
http://msdn.microsoft.com/en-us/library/bb351654.aspx
I hope this helps.
The DateTime object is format-independent (for the most part). So whether or not it starts in the format you list or not doesn't matter. You can always get it back into that format (using the ToString("o") function). But that's as a string (when format matters).
After a quick search, it looks like you must be talking about string format, even though you said no string. So the other answer or the ToString("o"); part of mine is relevant.

Convert facebook date time to C# date time

Hi i have notice there two date times facebook gives, one is a date time from Unix Epoch and other is RFC 3339 Datetime (if i am not wrong). I wanted to know what is the best way to convert between each other. I have tried DateTime.TryParse() method but some times it dosent return the correct parsed date. Like it gives 21-Dec-2010 7:21:56 AM for 2010-12-21T01:51:56+0000. But it seems it doesn't parse time correctly. So plese tell how to change between epoch times and above datetime in C# datetime.
DateTime.Parse is converting a UTC date to your local timezone.
To retrieve the original UTC date, call ToUniversalTime().

Categories

Resources