如何在JavaScript中将字符串转换为日期格式

如何在JavaScript中将字符串转换为日期格式,javascript,Javascript,如何使用JavaScript将字符串转换为日期 例如: Wed May 21 2014 02:40:00 GMT+0600 (Central Asia Standard Time) 我想将其转换为: YYYY-mm-dd H:i:s Date构造函数接受表示日期的字符串,例如: var date = new Date("Wed May 21 2014 02:40:00"); alert(date.getDate()); // 21 请参见您必须使用Date类使用以下方法解析字符串并设置其格

如何使用JavaScript将字符串转换为日期

例如:

Wed May 21 2014 02:40:00 GMT+0600 (Central Asia Standard Time)
我想将其转换为:

YYYY-mm-dd H:i:s

Date
构造函数接受表示日期的字符串,例如:

var date = new Date("Wed May 21 2014 02:40:00");
alert(date.getDate()); // 21

请参见

您必须使用Date类使用以下方法解析字符串并设置其格式:

  • Date.parse()
  • Date.toISOString()
例如:

var text = "Wed May 21 2014 02:40:00 GMT+0600 (Central Asia Standard Time)";
var date = new Date(Date.parse(text));
var formatedText = date.toISOString();
console.log(formatedText );
function pad(number) {
  if ( number < 10 ) {
    return '0' + number;
  }
  return number;
}


function toCustom(date) {
    return date.getUTCFullYear() +
    '-' + pad( date.getUTCMonth() + 1 ) +
    '-' + pad( date.getUTCDate() ) +
    ' ' + pad( date.getUTCHours() ) +
    ':' + pad( date.getUTCMinutes() ) +
    ':' + pad( date.getUTCSeconds() );
};
如果需要自定义格式,请尝试使用自定义格式化程序,例如:

var text = "Wed May 21 2014 02:40:00 GMT+0600 (Central Asia Standard Time)";
var date = new Date(Date.parse(text));
var formatedText = date.toISOString();
console.log(formatedText );
function pad(number) {
  if ( number < 10 ) {
    return '0' + number;
  }
  return number;
}


function toCustom(date) {
    return date.getUTCFullYear() +
    '-' + pad( date.getUTCMonth() + 1 ) +
    '-' + pad( date.getUTCDate() ) +
    ' ' + pad( date.getUTCHours() ) +
    ':' + pad( date.getUTCMinutes() ) +
    ':' + pad( date.getUTCSeconds() );
};
功能板(编号){
如果(数字<10){
返回“0”+数字;
}
返回号码;
}
函数toCustom(日期){
返回日期。getUTCFullYear()+
“-”+pad(date.getUTCMonth()+1)+
“-”+pad(date.getUTCDate())+
''+pad(date.getUTCHours())+
“:”+pad(date.getUTCMinutes())+
“:”+pad(date.getUTCSeconds());
};
这些可能非常有用:


    • 你甚至可以用我的插件翻译它。简单到:

      $(selector).setDate({format: "+Y-+m-+d +H:+ii:+ss"; date: 'Wed May 21 2014 02:40:00'});
      


      您也可以传递日期对象,无需获取日期字符串

      您的源字符串是什么,预期的日期是什么