简体   繁体   中英

Convert date string into proper date in Javascript

I get an array with dates as string from the server, now I want to filter only day, month and year. How can I format the filter result to a certain date format?

var date  = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00', ...];

//wanted result: 2015-02-04 or 04.02.2015

Date can take an argument of a string. Use a for loop to iterate through your list, and then make a new Date object for each one.

var date  = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00']
var dateObjects = [];

for (var i = 0; i<date.length; i++) {
  d = new Date(date[i]);
  dateObjects.push(d);
}

Or, in a single line:

var dateObjects = date.map( function (datestr) {return new Date(datestr)} );

Now, you can find the month, day, and year from one of these by the following methods:

var year = dateObjects[0].getFullYear(); // Gets the year
var month = dateObjects[0].getMonth()+1; // Gets the month (add 1 because it's zero-based)
var day = dateObjects[0].getDate(); // Gets the day of the month

dateObjects[0] is just an example that refers to the first date in the list.

So you can then get your output string like

var dateStrings = dateObjects.map(function (item) {
  return item.getFullYear()+"-"+(item.getMonth()+1)+"-"+item.getDate();
})

You could convert your what's look to be an ISO Date format like this:

var date  = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00'];

date.map(function(_d) {
    var d = new Date(_d)
    return d.getFullYear() + '-' + d.getMonth() + 1 + '-' + d.getDay()
}

// if you want to get fancy, you could throw in this function to pad the days and months:
var pad = function (n) {return n<10? '0'+n:''+n;}

var sorted = date.map(function(_d) {
    var d = new Date(_d)
    return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDay())
})
console.log(sorted);
var date  = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00'];
var newdateobject = [];

$.each( date, function(key, e) {
var a = new Date(e);
  newdateobject.push(a.getFullYear()+'-'+(a.getMonth()+1) +'-'+a.getDate());
});

IF the format you mentioned is consistent, then:

date.forEach(function(d) {
    d = d.substring(0, 10);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM