3

I have javascript date object which gives me a date string in this format, "Tue Sep 04 2012B0100 (GMT Daylight Time)"

I am trying to parse with ParseEaxcat as mentioned here, but it throws an invalid date exception - anyone point me in the direction of the right format

                string date = "Tue Sep 04 2012B0100 (GMT Daylight Time)";
                dt = DateTime.ParseExact(date,"ddd MMM dd yyyyBzzzz",
                     CultureInfo.InvariantCulture);

I've also looked at this with no joy: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Community
  • 1
  • 1
BikerP
  • 820
  • 1
  • 15
  • 25
  • 7
    I may be wrong, but I would imagine the dashes '-' in the format string are causing some grief here, since they aren't in the source string? – sybkar Sep 04 '12 at 16:50
  • It sounds like a nonstandard datetime format, are you sure the B is not a plus ? You might need to do some pre-processing on the string to get .NET to parse it. – driis Sep 04 '12 at 17:05
  • It might be bad to use InvariantCulture when you have English day and month names. – driis Sep 04 '12 at 17:06

6 Answers6

8

If you can (and it sounds like you do since you have the object), I'd recommend extracting the number of milliseconds since 1970/01/01 from Javascript (.getTime()), convert it to .Net ticks (100-nanosecond units), and use that to parse into a C# DateTime.

var ticks = (jsMillis * 10000) + 621355968000000000;
var date = new DateTime(ticks);

where jsMillis is the number you get from calling getTime() on the Javascript DateTime object.

The 621355968000000000 is to convert from C#'s date origin (Midnight Jan 1, 0001) to javascript's date origin.

PPC-Coder
  • 3,522
  • 2
  • 21
  • 30
  • 1
    +1 - Using `date.getTime()` in JS to get epoch time is the correct way to solve this. Trying to parse `date.toString()`'s result is fraught with peril. See also the [C# epoch conversion functions here](http://stackoverflow.com/q/2883576/201952). – josh3736 Sep 04 '12 at 17:50
  • it's not getTime() - consider using valueOf() which is the number of milliseconds from midnight January 1st 1970 – Yuki Jan 20 '14 at 06:17
3

This works. Though, you may want to strip the GMT Daylight Time portion out before passing it in just to avoid the in-line split.

string date = "Tue Sep 04 2012B0100 (GMT Daylight Time)";
var dt = DateTime.ParseExact(date.Split('(')[0].Replace("B","+").Trim(), "ddd MMM dd yyyyzzz", CultureInfo.InvariantCulture);

Edited to account for the offset.

J. Tanner
  • 575
  • 2
  • 10
  • You'll note if you ToString that dt you get something like 39/04/12. The 3 is your day of week. Just format it if you need to on the other side like; dt.ToString("mm/dd/yy"); – J. Tanner Sep 04 '12 at 17:09
  • this will work in the sense it won't throw an exception, but will it not just set the UTC offset as the Hours and minutes on the date? – BikerP Sep 05 '12 at 07:11
  • To parse the offset with zzz, it appears it looks for a + modifier. By replacing the B with a + that should get your desired result. – J. Tanner Sep 05 '12 at 19:16
3

I'm getting a different date time format from JavaScript. Here is what I had to do:

public void Main()
{
    Console.WriteLine(
        ConvertJsDate("Fri Apr 18 2014 16:23:18 GMT-0500 (Central Daylight Time)"));
    //test more regular date
    Console.WriteLine(
        ConvertJsDate("4/18/2014 16:23:18")); 
}

public DateTime ConvertJsDate(string jsDate)
{
    string formatString = "ddd MMM d yyyy HH:mm:ss";

    var gmtIndex = jsDate.IndexOf(" GMT");
    if (gmtIndex > -1) 
    {
        jsDate = jsDate.Remove(gmtIndex);
        return DateTime.ParseExact(jsDate, formatString, null);
    }
    return DateTime.Parse(jsDate);
}
What Would Be Cool
  • 6,204
  • 5
  • 45
  • 42
0

The date doesn't appear to match the format string. The format string has hyphens, and is missing the parenthesized section. Also, there is no mention of a format string with 4 z's, so you might change the first one to a 0.

djs
  • 220
  • 1
  • 5
0

Alternative approach is to convert date into reasonable representation on JavaScript side will be significantly more robust: no need to guess language server side, may handle timezones correctly.

If you use some sort of automated conversion (i.e. JSON.stringify) you may need to add one more field parallel to your date field with string representation of the same value and use it on server side instead of original one.

{ dateFied: new Date(),
  dateFiledAsIsoString: "....." }

If decided to go this route consider also passing Time Zone (time offset) to server side code or converting time to UTC on JavaScript side. Consider using ISO8601 format for date: yyyy-MM-ddTHH:mm:ss.fffffffzzz.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • You're right on the first part - JS should convert the `Date` into a more reliable representation. However, rather than dealing with strings, just use `getTime()` to get the number of ticks since epoch. That way, you don't have to worry about timezones at all. – josh3736 Sep 04 '12 at 17:53
  • @josh3736, I'm not exactly sure how you can get away from not dealing with timezones if you use ticks (unless you convert to UTC first and than to ticks, which I think is not what you are suggesting)? – Alexei Levenkov Sep 04 '12 at 18:58
  • `getTime` always deals in UTC automatically. – josh3736 Sep 04 '12 at 19:09
  • @josh3736, care to provide a link? To my knowledge it is simply offset from particular moment in local time (January 1, 1970), but you can't convert number like 1346789616870 to correct time without knowledge of timezone it was computed... – Alexei Levenkov Sep 04 '12 at 20:18
  • 2
    [`getTime` on MDN](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getTime): *"Returns the numeric value corresponding to the time for the specified date **according to universal time**."* – josh3736 Sep 04 '12 at 20:20
0

There are a lot of ways to do this... But this is what I find to be the simplest...

// JavaScript
var d = new Date();
d.toLocaleString();
// =>   "6/26/2015, 2:07:25 PM"

// Can be Parsed by the C# DateTime Class
DateTime d = DateTime.Parse( @"6/26/2015, 2:07:25 PM" );
Console.WriteLine( d.ToLongDateString() );
// =>   Friday, June 26, 2015
tpayne84
  • 181
  • 1
  • 9