javascript中的时间戳格式

时间:2014-07-11 13:44:14

标签: javascript jquery

我希望使用JavaScript将2014-07-24 17:35:00的日期格式设置为24-07-2014 17:35:00

我试过这种方式,

datestring = '2014-07-24 17:35:00';

function formatDate(datestring) {
    var m_names = new Array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12");
    var d = new Date(datestring);
    //var d = new Date(datestring * 1000);
    var curr_date = d.getDate();
    var curr_month = d.getMonth();
    var curr_year = d.getFullYear();
    var hours = d.getHours();
    var minutes = d.getMinutes();
    var result = curr_date + "-" +m_names[curr_month]  + "-" + curr_year+' '+hours+':'+minutes;
    alert(result);
    return result;
}

但我收到错误NaN-undefined-NaN NaN:NaN。感谢帮助。

3 个答案:

答案 0 :(得分:1)

我认为你有简单的方法来解决这个问题。

试试这个。

function myFunction() {

      var d = new Date("2014-07-24 17:35:00");
      var n = d.toLocaleDateString('en-GB');
      var t = d.toLocaleTimeString('en-GB')
      var r = n.replace(new RegExp('/', 'g'),'-')
      document.getElementById("demo").innerHTML = replase +" "+t; 
}

答案 1 :(得分:0)

我尝试了你的代码,看看我发现了什么

var datestring = '2014-07-24 17:35:00';

$("#date").val(formatDate1())
$("#date2").val(formatDate())

function formatDate1(datestring) {
var m_names = new Array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12");
  var d = new Date(datestring);
  //var d = new Date(datestring * 1000);
  var curr_date = d.getDate();
  var curr_month = d.getMonth();
  var curr_year = d.getFullYear();
  var hours = d.getHours();
  var minutes = d.getMinutes();
  var result = curr_date + "-" +m_names[curr_month]  + "-" + curr_year+' '+hours+':'+minutes;

  return result;
}

function formatDate() {
  var m_names = new Array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12");
  var d = new Date(datestring);
  //var d = new Date(datestring * 1000);
  var curr_date = d.getDate();
  var curr_month = d.getMonth();
  var curr_year = d.getFullYear();
  var hours = d.getHours();
  var minutes = d.getMinutes();
  var result = curr_date + "-" +m_names[curr_month]  + "-" + curr_year+' '+hours+':'+minutes;

  return result;
}

所以你的问题是参数" datestring"因为它隐藏了同名的变量

在这里,您可以看到Fiddle example

答案 2 :(得分:0)

解决方案低于代码:

function transformDate(dateString) {
  var dateTimeParts = dateString.split(' ');
  var dateParts = dateTimeParts[0].split('-');
  return [[dateParts[2], dateParts[1], dateParts[0], ].join('-'), dateTimeParts[1]].join(" ");
}

var newDate = transformDate('2014-07-24 17:35:00');
console.log(newDate);

如果您需要更灵活的代码,包括使用本地化,您也可以考虑使用moment.js库。