-3

how can I convert "/Date(1479250800000)/" String to a C# Datetime?

Thanks in advance

MKP
  • 117
  • 3
  • 14
  • that's not a javascript date string it came from your back end code in the first place – charlietfl Jan 04 '17 at 07:53
  • is this jsonresult – Pathik Tailor Jan 04 '17 at 08:22
  • I know, but I need to store it in a string because this field can contain any type of data. In JS I would create the date using moment("/Date(1479250800000)/") but I don't know how to get the same result in C#. Big thanks – MKP Jan 04 '17 at 08:38

2 Answers2

1

Assuming the value inside the brackets is number of ticks:

var datstr = "/Date(1479250800000)/";
long ticks = Convert.ToInt64(datstr.Substring(6, 13));
DateTime date = new DateTime(ticks);

There will be a difference between .Net and javascript tick value:

The JavaScript Date type's origin is the Unix epoch: midnight on 1 January 1970. The .NET DateTime type's origin is midnight on 1 January 0001. If by "ticks" you mean something like "milliseconds since the epoch", you can call ".getTime()

There are 621355968000000000 epoch ticks for javascript from Ist Jan 1900 to Ist Jan 1970. And here 10000 are the ticks per milliseconds.

quoted from here. You will need to correct for this. the last line would look like the following:

DateTime date = new DateTime(ticks * 10000 + 621355968000000000);
Community
  • 1
  • 1
martijn
  • 1,417
  • 1
  • 16
  • 26
  • Using this code I get a date ( {02/01/0001 17:05:25} ) but the original date was "Wed Nov 16 2016 00:00:00 GMT+0100". Could it be a problem with the date format? I need to use dd/mm/yyyy. Thanks in advance. – MKP Jan 04 '17 at 09:15
0

You'll get the string "/Date(1479250800000)/" as a date value in javascript if you are sending it from C#. But if you sending back the value to a date field in C# then the value will be deserialized as DateTime value. You don't need to convert it explicitly, just get it in a DateTime field.

Karthik AMR
  • 1,694
  • 21
  • 29
  • You're right but I need to deserialize it as String because this field can contain any type of data. I just need to convert that string in a valid DateTime. Big thanks. – MKP Jan 04 '17 at 09:25