Convert JSON date to C# datetime variable - c#

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

Related

DateTime.ParseExact Failing to convert to correct date

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 ?

DateTime ParseExact not working when changing time

I'm having trouble figuring out why my date is parsed correctly until I change the time of the date passed into the parse method.
var parsedDate = DateTime.ParseExact("2016-02-05T07:00:00+00:00", "yyyy-MM-ddThh:mm:ss+00:00", CultureInfo.InvariantCulture);
dateValueToTryParse = parsedDate.ToString("dd/MM/yyyy");
The required result is outputted and I do get 05/02/2016. However, if I change the string passed in to:
2016-02-19T23:59:00+00:00
The output of dateValueToTryParse remains the same and it is not parsed correctly. Am I doing anything particularly wrong with my parsing? I'm confused as the format seems to be exactly the same?
You need to change your incoming format to yyyy-MM-ddTHH:mm:ss+00:00.
The difference is HH. Capital H means 24 hour clock or "military time".
Otherwise, it is trying to parse hour 23 which doesn't exist.
See here for more detailed information on other formats: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
Changing hh to HH specifier can solve your problem but since your string has an UTC offset value, I would prefer to parse it to DateTimeOffset instead of DateTime for consistency.
var dto = DateTimeOffset.ParseExact("2016-02-05T23:00:00+00:00",
"yyyy-MM-ddTHH:mm:sszzz",
CultureInfo.InvariantCulture);
Now, you have a DateTimeOffset as {05.02.2016 23:00:00 +00:00} and you can use it's .DateTime property to get the DateTime value represented by it.
var dateValueToTryParse = dto.DateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
This will generate 05/02/2016 as a result.

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

Convert date to specific format if I don't know source date format

I want to convert date to a specific format (e.g. en-US MM/dd/yyyy) and I am aware about normal method to parse it.
But in my case I'm unaware about the source date format. Source date format is subject to change as per server environment. It can be en-US or en-GB.
e.g. DateTime dt = DateTime.Now;
'dt' can be '27/03/2014' or '03/27/2014'.
How to convert the source date to en-US format if I don't know source date format?
(string format would be fine - MM/dd/yyyy e.g. "03/27/2014").
If you don't know the source format, there is a chance of getting errors while trying to convert. For example, try converting:
05/01/2013
A computer wouldn't be able to identify the date in such a case. It could result in two outputs: 05 Jan, 2013 or 01 May, 2013.
DateTime.Now.toString("yyyy-MM-dd"); //toString(specify format)
try this one
DateTime result;
if (!DateTime.TryParseExact(inputString, "dd/MM/yyyy", out result)
result = DateTime.ParseExact(inputString, "MM/dd/yyyy");
OR
DateTime result;
if (!DateTime.TryParse(inputString, out result)
result = DateTime.ParseExact(inputString, CultureInfo.InvariantCulture, DateTimeStyles.None);
If you know your environment will always be the deciding factor, why not just use that?
Try some variation of the following:
string yourFormat = ... // Whatever is your default format
if(Thread.CurrentThread.CurrentCulture.Name == "en-US")
{
yourFormat = "MM/dd/yyyy";
}
else (if Thread.CurrentThread.CurrentCulture.Name == "en-GB")
{
yourFormat = "dd/MM/yyyy";
}
DateTime d = DateTime.ParseExact(inputString, yourFormat, null)
How to convert the source date to en-US format if I don't know source date format?
You need to know the source date format, only then can you convert it to the required date format.
As wiero has rightly said in the comments "If you have 01/02/2014 depending its 1 February or 2 January. You have to know how to read it".
The default format of the object returned by DateTime.Now will be the one specified in your server setting, check the screenshot below:
Referring to #DarkWanderer's comment in question:
DateTime object has nothing to do with format.
Just needed to convert it to the specific format using ToString("MM/dd/yyyy").
I was using Parse() method to convert but it will not work. BToString() method is surely a way.
This will work: dt.Tostring("MM/dd/yyyy");
Thanks #DarkWanderer.

Convert javascript date time to C#/VB.NET date time

I want to get client timezone so i'm using the code below
function filltime()
{
document.getElementById("hdnTime").value = new Date();
}
conversion
Dim time As Date = DateTime.ParseExact(hdnTime.Value,
"ddd MMM d HH:mm:ss UTCzzzzz yyyy",InvariantCulture)
I'm not getting exact value. Its showing server time only.
But hdnTime.Value contains the correct value("Mon Feb 18 14:46:49 UTC+0530 2013"). I think the problem is with conversion.
What is the problem? How can I solve?
Dates and times are a pain in 1 language, let alone when passing a value between 2.
I'd recommend serializing the JavaScript Date() object into JSON before posting it back to the server. Then de-serializing it into a C# DateTime object using a library such as JSON.NET. There's comprehensive documentation (Serializing Dates in JSON) with regards to what settings can be applied when serializing and de-serializing.
JavaScript
function filltime()
{
document.getElementById("hdnTime").value = JSON.stringify(new Date());
}
JSON isn't native to every browser, so you mean need to manually load it in, for more information you can refer to: Browser-native JSON support (window.JSON)
C# using JSON.NET
DateTime dateTime = JsonConvert.DeserializeObject<DateTime>(hdnTime.Value);
You are confusing the DateTime object with its displaying
it is normal that you see the server time because you are seeing the datetime rappresentation with your current timezone.
What you don't get is how DateTime works...
If you pass a datetime with timezone info then it will be converted to your timezone with the right offset.
If you want to pass a datetime and get it as it is than you have to remove the timezone part.
In you situation, anyway, if you need only to know the client timezone just pass it!
var d = new Date()
var n = d.getTimezoneOffset();
The getTimezoneOffset() method returns the time difference between UTC time and local time, in minutes.
For example, If your time zone is GMT+2, -120 will be returned.
For general discussion:
in my experience the best way to deal with datetime converted as string and passed between different systems, is to use the ISODATE format:
DateTime.Now.ToString("s"); //"2013-02-18T11:17:24"

Categories

Resources