Javascript formatting date

How to format this:

/Date(1292962456255)/ 

how is regular search date in javascript / jQuery?

+4
source share
4 answers

This is what I call the "Microsoft date" and the following function will convert the encoded date to javascript date

  var msDateToJSDate = function(msDate) { var dtE = /^\/Date\((-?[0-9]+)\)\/$/.exec(msDate); if (dtE) { var dt = new Date(parseInt(dtE[1], 10)); return dt; } return null; } 
+3
source

Check out moment.js ! This is a "small javascript date library for parsing, managing and formatting dates." This is a really powerful library.

Here is an example ...

 var today = moment(new Date()); today.format("MMMM D, YYYY h:m A"); // outputs "April 11, 2012 2:32 PM" // in one line... moment().format("MMMM D, YYYY h:m A"); // outputs "April 11, 2012 2:32 PM" 

Here is another example ...

 var a = moment([2012, 2, 12, 15, 25, 50, 125]); a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, March 12th 2012, 3:25:50 pm" a.format("ddd, hA"); // "Mon, 3PM" a.format("D/M/YYYY"); // "12/3/2012" 

In addition, checkout date.js is worth noting. I think the two libraries complement each other.

+2
source

A number is a timestamp with millisecond resolution. This number can be passed to the JavaScript constructor of the Date class. All that is needed is some code to extract from a string:

 var dateString = "/Date(1292962456255)/"; var matches = dateString.match(/^\/Date\((\d+)\)\/$/); var date = new Date(parseInt(matches[1], 10)); 

The regular expression in the second line becomes a bit messy, since the line contains /, (and) exactly at the positions that they are needed in the regular expression (you are sure that you have lines that look like this, and not a description of the pattern that will be their to extract?).

Another way to do this is to use eval :

 var dateString = "/Date(1292962456255)/"; var date = eval("new " + dateString.substring(1, dateString.length - 1)); 

but this may open up to an XSS attack, so I do not recommend it.

0
source

I think this is microtime . Similar to PHP microtime . Or in new Date().getTime() in JavaScript.

 // PHP $ php -r "var_dump(microtime(true));" float(1292963152.1249) // JavaScript new Date().getTime() 1292963411830 
-2
source

Source: https://habr.com/ru/post/1332955/


All Articles