I have javascript date object which gives me a date string in this format, "Wed Dec 16 00:00:00 UTC-0400 2009".
I pass this via Ajax to the server (ASP.NET c#)
How can I convert, "Wed Dec 16 00:00:00 UTC-0400 2009" to a C# DateTime object. DateTime.Parse fails.
You can use DateTime.ParseExact which allows you to specify a format string to be used for parsing:
DateTime dt = DateTime.ParseExact("Wed Dec 16 00:00:00 UTC-0400 2009",
"ddd MMM d HH:mm:ss UTCzzzzz yyyy",
CultureInfo.InvariantCulture);
The most reliable way would be to use milliseconds since the epoch. You can easily get this in JavaScript by calling Date.getTime(). Then, in C# you can convert it to a DateTime like this:
long msSinceEpoch = 1260402952906; // Value from Date.getTime() in JavaScript
return new DateTime(1970, 1, 1).AddTicks(msSinceEpoch * 10000);
You have to multiply by 10,000 to convert from milliseconds to "ticks", which are 100 nanoseconds.
This may not be possible in your case, but I really recommend updating the JS code to pass dates/times in ISO 8601 format. http://en.wikipedia.org/wiki/ISO_8601
ISO 8601 is not only the formal standard, it's also easy to use and prevents a lot of timezone hassle!
To get 8601 datetime strings in Javascript:
var d = new Date();
var iso_time = d.toISOString(); //"2014-05-06T18:49:16.029Z"
To read 8601 datetime strings in C#:
DateTime d = DateTime.Parse(json_string);
Just for posterity, to help future fellow Googlers, I'd like to expand on EMP's answer.
EMP's answer provides the time in UTC (if that's what you're looking for, use that).
To arrive at the client local time in C#:
In JavaScript:
var now = new Date();
var UTC = now.getTime();
var localOffset = (-1) * now.getTimezoneOffset() * 60000;
var currentTime = Math.round(new Date(UTC + localOffset).getTime());
In C#:
DateTime currentTimeDotNet = new DateTime(1970, 1, 1).AddTicks(Convert.ToInt64(currentTime) * 10000);
Credit to this blog and EMP's answer, but took some trial and error on both ends to get it right, so just fyi for future folks.
To be honest I wouldn't try to parse that date string in C#, I'd personally try to create a more useful date structure from your javascript date object.
For instance you could use parse() in javascript which will return the ms representing the date object, which you can use DateTime.Parse() on to convert into a C# DateTime object.
Related
How would you handle the following string value that needs to be converted to a DateTime object?
"2015/01/22 12:08:51 (GMT+09:00)"
Would like to include this as a recognized DateTime pattern. As I encounter other formats, I would like to just implement a new pattern.
Here a piece of code that will successfully parse the given string (notice DateTimeOffset rather than DateTime):
var str = "2015/01/22 12:08:51 (GMT+09:00)";
var dt = DateTimeOffset.ParseExact
(str,
"yyyy/MM/dd HH:mm:ss (\\G\\M\\TK)",
System.Globalization.CultureInfo.InvariantCulture
);
//dt now has +9:00 offset - that's correct only if GMT is provided as UTC.
More info at The Difference Between GMT and UTC
This code takes a string and converts it into a DateTime object
DateTime myDate = DateTime.Parse("2017-08-28 14:20:52,001", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture);
All you need to do is create a format that matches your input. This link helps:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
For more details read this: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/how-to-convert-a-string-to-a-datetime
Here there is the official documentation of DateTime.Parse with some examples. It covers also the case of other formats
https://msdn.microsoft.com/it-it/library/system.datetime.parse(v=vs.110).aspx
Using DateTime.ParseExact is probably your best bet. It takes in an input string and an expected format string that the input should match. It will return true if the conversion was successful, and the out parameter will be the result of the conversion (result in the example below).
I was unable to get it to work without forcibly removing the "GMT" portion, but if that's acceptable to you, the code below should work.
This example takes the original input and converts it to UTC time (i.e. it adjusts the time based on your GMT value, which is to subtract 9 hours in your example):
var input = "2015/01/22 12:08:51 (GMT-08:00)";
var format = "yyyy/MM/dd H:mm:ss (zzz)";
DateTime result;
// Remove the "GMT" portion of the input
input = input.Replace("GMT", "");
if (DateTime.TryParseExact(input, format, CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal, out result))
{
Console.WriteLine($"'{input}' converts to {result} UTC time.");
}
else
{
Console.WriteLine($"'{input}' is not in the correct format.");
}
This example is modified from the ones on the DateTime.TryParseExact documentation.
I have date and time strings already in UTC. I need to use those strings to create a DateTime object.
This is the code I'm using. The problem is the time gets converted and my UTC time on the datetime object is no longer correct. I'm giving UTC values so they shouldn't get converted again.
string format = $"{dateFormat}_{timeFormat}";
string value = $"{dateValue}_{timeValue}";
var x = DateTimeOffset.ParseExact(value, format, CultureInfo.CurrentCulture).UtcDateTime;
where dateFormat = "ddMMyy", timeFormat = "HHmmss", dateValue = "191194" and timeValue = "225446".
D Stanley's answer certainly works, but is slightly more complex than you need - if you want a DateTime as the result, you don't need to use DateTimeOffset at all, as DateTime.ParseExact handles DateTimeStyles.AssumeUniversal as well, although you need to specify AdjustToUniversal so that the result is in UTC. (Otherwise it's adjusted to the local time zone automatically - and unhelpfully, IMO, but that's a battle for another day.)
var x = DateTime.ParseExact(
value,
format,
CultureInfo.CurrentCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
Sample code (that revealed to me the need for DateTimeStyles.AdjustToUniversal):
using System;
using System.Globalization;
class Test
{
static void Main(string[] args)
{
string text = "2015-06-10 20:52:13";
string format = "yyyy-MM-dd HH:mm:ss";
var dateTime = DateTime.ParseExact(
text,
format,
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
Console.WriteLine(dateTime); // 10/06/2015 20:52:13 on my box
Console.WriteLine(dateTime.Kind); // Utc
}
}
I'd be careful using CultureInfo.CurrentCulture, by the way - bare in mind the fact that it can affect the calendar system in use as well as format strings etc.
(As a side-note of course, I'd recommend using my Noda Time library instead. In this case I'd probably suggest parsing your time using a LocalTimeFormat, your date using a LocalDateFormat, then adding the results together to get a LocalDateTime that you could then convert to a ZonedDateTime using UTC. Or you could use your existing approach to create a ZonedDateTimePattern or InstantPattern, of course.)
Use the overload of DateTimeOffset.ParseExact that takes a DateTimeStyles value:
var x = DateTimeOffset.ParseExact(value,
format,
CultureInfo.CurrentCulture,
DateTimeStyles.AssumeUniversal)
.UtcDateTime;
Note that the call to UtcDateTime doesn't hurt anything, but the time will already be in UTC time (which is what you want) so it will give you back the equivalent DateTime value. You can just use DateTime.ParseExact as Jon suggests, which has the same overload.
This solution also will be helpful if you have your date not as one string.
Just use DateTimeKind.Utc as constructor parameter of DateTime:
new DateTime(2020, 05, 07, 18, 33, 0, DateTimeKind.Utc);
i want to calculate a checktime to the time now and get the hours.
I have a string "time" for example...
Jun 06 2013 07:23:06
and with DateTime.Now I get the Time now. The Problem is now that i can't calculate the difference :(
I need them in my Project where I get from the License Server the time from a user and I want to show the difference to now. I want show this in hours.
You can use the Parse method of the DateTIme class to parse a string as a date and the subtract that from now.
TimeSpan diff = DateTime.Now - DateTime.Parse(dateString);
var hours = diff.Hours
The above exsmple of course requires the date to be in a specific format. You can if needed use DateTIme.ParseExact and specify a specific format yourself
You need to first convert your string to DateTime. here you have custom format so you can use DateTime.ParseExact or DateTime.TryParseExact method as below
DateTime dt;
if (DateTime.TryParseExact("Jun 06 2013 07:23:06", "MMM dd yyyy HH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// get difference
var inDays = (DateTime.Now - dt).Days;
}
You can use TimeSpan.Hours property like;
Gets the hours component of the time interval represented by the
current TimeSpan structure.
string dateString = "Jun 06 2013 07:23:06";
var differenceHours = (DateTime.Now - DateTime.Parse(dateString)).Hours;
Console.WriteLine(differenceHours);
Here a DEMO.
If you want to convert your custom formatted string to DateTime, you can use DateTime.ParseExact which need exact format matching between string and datetime.
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.
u may try it
DataTime diff = DateTime.Now - Convert.ToDataTime(dateString);
var hours = diff.Hours
I have some JavaScript code that I'm trying to pass to my web service. My JavaScript code is supposed to send a date in UTC format. Locally, the time that I generated my code at was at 12:30:43 pm. When I executed my JavaScript code, the following date/time was generated:
2012-06-03T20:30:43.000Z
That date/time was generated from this code:
var now = new Date();
var utcDate = new Date(
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds()
);
When I pass the date/time from JavaScript back to my web service, it is serialized as shown here:
20120603163043
That looks correct to me at this point. I then need to take that string and convert it to a date/time in C#. In an attempt to do that, I'm using the following C# code:
DateTime _value = DateTime.MinValue;
DateTime.TryParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out _value)
When that happens, I get the following date/time.
6/3/2012 12:30:43 PM
What am I doing wrong? I was expecting the date/time to be 6/3/2012 4:30:43 PM
The result you get is correct, but please check the Kind property of your DateTime. You'll notice it's not set to UTC but to Local.
You can use DateTimeStyles.AdjustToUniversal to generate a DateTime with Kind set to UTC.
DateTime dateTime;
DateTime.TryParseExact(
value,
"yyyyMMddHHmmss",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
out dateTime);
See it working on ideone.
If you just want to serialize using (e.g. webAPI) I find JS toISOString very useful and compatible.
//JAVASCRIPT
var d = new Date();
$toPut.dateTime = d.toISOString();
$toPut.put()
//C#
[Put("/setup/dateTime"), HttpPut]
public HttpResponseMessage SetDateTime([FromBody]DateTime dateTimeSettings )
That way you can keep your data structure and not deal with parsing.
You must pass date parameter to web service as UTC format and then use TryParse method to convert it to C# date object.
Try this:
//Javascript
var now = new Date(); //just like: 'Thu, 21 Mar 2013 12:44:40 GMT'
var utcNowString = now.toUTCString(); //pass this parameter to your web service
And this is C# code:
DateTime date;
DateTime.TryParse(jsDateString, out date); //parsed as: '21.03.2013 14:44:40'
Hope this helps.
If I have a timestamp in the form: yyyy-mm-dd hh:mm:ss:mmm
How can I just extract the date from the timestamp?
For instance, if a timestamp reads: "2010-05-18 08:36:52:236" what is the best way to just get 2010-05-18 from it.
What I'm trying to do is isolate the date portion of the timestamp, define a custom time for it to create a new time stamp. Is there a more efficient way to define the time of the timestamp without first taking out the date, and then adding a new time?
DateTime.Parse("2010-05-18 08:36:52:236").ToString("yyyy-MM-dd");
You should use the DateTime type:
DateTime original = DateTime.Parse(str);
DateTime modified = original.Date + new TimeSpan(13, 15, 00);
string str = modified.ToString("yyyy-MM-dd HH:mm:ss:fff");
Your format is non-standard, so you'll need to call ParseExact instead of Parse:
DateTime original = DateTime.ParseExact(str, "yyyy-MM-dd HH:mm:ss:fff", CultureInfo.InvariantCulture);
You could use substring:
"2010-05-18 08:36:52:236".Substring(0, 10);
Or use ParseExact:
DateTime.ParseExact("2010-05-18 08:36:52:236",
"yyyy-MM-dd HH:mm:ss:fff",
CultureInfo.InvariantCulture)
.ToString("yyyy-MM-dd");
DateTime date;
if (DateTime.TryParse(dateString, out date))
{
date = date.Date; // Get's the date-only component.
// Do something cool.
}
else
{
// Flip out because you didn't get a real date.
}
Get the .Date member on the DateTime
DateTime date = DateTime.Now;
DateTime midnightDate = date.Date;
use it like this:
var x = DateTime.Now.Date; //will give you midnight today
x.AddDays(1).AddTicks(-1); //use these method calls to modify the date to whats needed.
The best (and fastest) way to do this is to convert the date to an integer as the time part is stored in the decimal part.
Try this:
select convert(datetime,convert(int, #yourdate))
So you convert it to an integer and then back to a data and voila, time part is gone.
Of course subtracting this result from the original value will give you the time part only.