Javascript date format (prefer moment)

2019-06-10 11:16发布

问题:

I have date string as shown below. I want to be format like as YYYY-MM-DD HH:mm:SS please help me.

var str1 = '2018-02-20T10:10:00.000+01:00'; 

Formatted -> '2018-02-20 10:10:00'

var str2 = '2018-02-20T11:50:00.000+00:00';

Formatted -> '2018-02-20 11:50:00'

Thank you

回答1:

As you prefer moment, it should be easy if you use format method.

var offset = moment().utcOffset() - moment(str).utcOffset();

console.log(moment(str).add(offset, 'minute').format('YYYY-MM-DD hh:mm:ss'));

For more information - http://momentjs.com/docs/#/displaying/format/



回答2:

Here you have an example of code:

function formatDate(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ":" + seconds;
  return  date.getFullYear() + "/" + (date.getMonth()+1) + "/" + date.getDate()+ " " + strTime;
}

var d = new Date();
var e = formatDate(d);
alert(e);

And here you have the jsfiddle example: https://jsfiddle.net/6ccvkg5j/



回答3:

Thank you @emil. My answer is like:

var str = '2018-02-20T03:10:00.000-01:00';
var offset = moment().parseZone().utcOffset() - moment.parseZone(str).utcOffset();
var result = moment(str).add(offset * -1, 'minute').format('YYYY-MM-DD HH:mm:SS');