2011-12-01 70 views
0
function formatDate (input) { 
    var datePart = input.match(/\d+/g), 
    year = datePart[0].substring(2), // get only two digits 
    month = datePart[1], day = datePart[2]; 

    document.write(new Date(day+'/'+month+'/'+year)); 
} 

formatDate ('2010/01/18'); 

获取当前时间当我打印这我得到Thu Jun 01 1911 00:00:00 GMT+0530 (India Standard Time)但系统实际上3:42 P.M从日期对象

+0

您应该使用更通用的'yyyy/mm/dd'来使用'new Date'创建日期 – KooiInc

回答

0

用途是检索时的当前日期和包括在新的日期。例如:

var now = new Date, 
    timenow = [now.getHours(),now.getMinutes(),now.getSeconds()].join(':'), 
    dat = new Date('2011/11/30 '+timenow); 
0

你必须给时间:

//Fri Nov 11 2011 00:00:00 GMT+0800 (中国标准时间) 
alert(new Date("11/11/11")); 

//Fri Nov 11 2011 23:23:00 GMT+0800 (中国标准时间)  
alert(new Date("11/11/11 23:23")); 
0

你想干什么?只是时间?或者你想定义一种格式?铜是代码预计这种格式日期:日/月/年,改变了这种以YYYY/MM/DD

尝试这种情况:

function formatDate (input) { 
    var datePart = input.match(/\d+/g), 
    year = datePart[0], 
    month = datePart[1], day = datePart[2], 
    now = new Date; 

    document.write(new Date(year+'/'+month+'/'+day+" " + now.getHours() +':'+now.getMinutes() +':'+now.getSeconds())); 
} 

formatDate ('2010/01/18') 

输出:

Mon Jan 18 2010 11:26:21 GMT+0100 
0
  1. 传Date构造函数的字符串不必要的复杂。你只需要把这个值如下:

    new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10)) 
    
  2. 你创建一个没有指定时间日期()对象,所以它的到来了午夜。如果你想添加当前的日期和时间,创建不带参数的新日期,从它借用时间:

    var now = new Date(); 
    var myDate = new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10), 
        now.getHours(), now.getMinutes(), now.getSeconds()) 
    
  3. 无需最后两个字符去掉了一年。 “2010”是一个非常好的一年。