0

I have a c# DateTime that shows up as Date(1309513219184) when I try to include it in my web page with javascript. I would like it to show as something like 07/01/2011 09:30.

Is there a way that I can format this in javascript or should I first do some kind of c# format and then print as a javascript string?

How can I format it?

Robert Dawson
  • 153
  • 1
  • 2
  • 10

4 Answers4

1

You can do this:

var d = new Date(milliseconds);
// var d = new Date(dateString);
// var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
d.toString();    // or d.toLocaleString()

Or you can use a library like datejs

Mrchief
  • 75,126
  • 20
  • 142
  • 189
  • datejs is really for parsing dates and manipulating them with some logic, not really display/format. – Matt Jul 01 '11 at 03:20
  • You can pass a variety of format strings to it's `toString` method to get the desired formatted output: http://code.google.com/p/datejs/wiki/APIDocumentation#toString – Mrchief Jul 01 '11 at 03:22
  • good to know! I was not aware datejs supported this functionality – Matt Jul 01 '11 at 03:24
1

You can format in javascript. There already same questions posted earlier in StackOverflow.

How can I convert string to datetime with format specification in JavaScript?

Community
  • 1
  • 1
AjayR
  • 4,169
  • 4
  • 44
  • 78
0

From How do I format a Microsoft JSON date? we can see that you can parse the date out using:

var date = new Date(parseInt(jsonDate.substr(6)));

Substring without the 2nd argument will take the substring from the starting index to the end, giving you:

1309513219184)

Which JavaScript can successfully parse into an int of value 1309513219184. This value represents the number of millseconds since 1 January 1970 00:00:00 UTC.

As for formatting, my personal preference is the date.format.js. For example:

dateFormat(date, "mm/dd/yyyy hh:MM:ss")
Community
  • 1
  • 1
Matt
  • 41,216
  • 30
  • 109
  • 147
  • I wish I didn't have to load another js :-( – Robert Dawson Jul 01 '11 at 03:38
  • You can certainly accomplish string output with on your own using the getMonth, getMinutes, etc that are built-in (https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) – Matt Jul 01 '11 at 03:42
0

I would change the DateTime variable into a string with the desired format in your C# code before sending the value to the client. You could use the String.Format method for this:

var newDateTime = Format.String("{MM/dd/yyyy hh:mm}", oldDateTime);

Drew
  • 71
  • 2
  • This isn't practical if you are serializing your data in JSON format. The given form in the question is in fact what you get when serializing a Date object into JSON from C#. Plus, if you actually want to operate on the resulting Date, you'd still have to parse it anyway. – Matt Jul 01 '11 at 03:29