1

My application is getting a datetime value from JSON in the following format:

Created "/Date(1335232596000)/" 

To show the value on the front end, I wrote a js function with the following code:

 return new Date(parseInt(date.substr(6))); 

This however, shows the following:

Mon Apr 23 2012 20:56:36 GMT-0500 (Central Daylight Time) 

Any suggestions on how can I get the date to display like this:

"04/23/2012 - 08:56:26pm CST" 
2
  • Do you always want it in Standard time, even if it is currently Daylight time? Do you also want Central time every time, or to use the current browser time zone? Commented Aug 17, 2012 at 22:36
  • possible duplicate of Formatting a date in JavaScript Commented Aug 18, 2012 at 9:32

4 Answers 4

2

Use the official jQuery Globalization Plugin format method:

Globalize.format( new Date(1955,10,5), "yyyy/MM/dd" ); // "1955/11/05" Globalize.format( new Date(1955,10,5), "dddd MMMM d, yyyy" ); // "Saturday November 5, 1955" 

There are a ton of date formatting options available.

Sign up to request clarification or add additional context in comments.

Comments

2

You will need to format your date using the date object methods: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

Or use some external library like Datejs.

Here is a question about this: Where can I find documentation on formatting a date in JavaScript?

Comments

2

Date is an Javascript object. You can format it by using the Date Object Methods http://www.w3schools.com/jsref/jsref_obj_date.asp

var mydate = new Date() var hours = mydate.getHours() 

Comments

1

My application is getting a datetime value from JSON in the following format:

Created "/Date(1335232596000)/"

Instead of using a DateTime property on your view model that is serialized by the JavaScriptSerializer using the aformentioned format, use a string property and do the formatting on the server => use a real view model.

Here's how you could format this DateTime

DateTime date = ... string created = date.ToString("MM/dd/yyyy hh:mm:sstt ") + GetTimeZoneName(date); // pass the created string to the view 

where TimeZoneName is defined like this:

public static string GetTimeZoneName(DateTime date) { var name = TimeZone.CurrentTimeZone.IsDaylightSavingTime(date) ? TimeZone.CurrentTimeZone.DaylightName : TimeZone.CurrentTimeZone.StandardName; var newName = ""; var parts = name.Split(' '); foreach (var s in parts) { if (s.Length >= 1) { newName += s.Substring(0, 1); } } return newName; } 

Now inside your view you will receive the date formatted as it has to be formatted. And if for some reason you also needed this date under the form of a javascript Date object inside the view you could also leave the DateTime property on the view model and the serializer will include both.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.