将Java日期字符串转换为javascript日期

时间:2011-01-13 11:40:59

标签: javascript string json date

当我通过JSON从Java发送日期到Javascript时,它会发送如下内容:

var ds = "11:07:47 13/01/2011";

Javascript无法将此字符串解析为日期

var d = new Date(ds);

有什么想法吗?

4 个答案:

答案 0 :(得分:14)

你需要一些JS解析String并在字符串中返回年,月,日,分,小时,秒:

var hour = ds.split(":")[0],
    minute = ds.split(":")[1],
    last_part = ds.split(":")[2],
    second = second_part.split(" ")[0],
    last_part2 = second_part.split(" ")[1],
    day = last_part2.split("/")[0],
    month =  last_part2.split("/")[1],
    year =  last_part2.split("/")[2];

然后实例化Date构造函数:

var d = new Date ( year, month, day, hour, minute, second );

答案 1 :(得分:4)

为了安全起见,您应该在Java中获得以毫秒为单位的时间并通过JSON将其发送到JavaScript。在那里你可以使用

var d = new Date();
d.setTime(valueInMilliseconds);

答案 2 :(得分:3)

您可以通过多种方式调用Date构造函数 来自http://www.w3schools.com/js/js_obj_date.asp的参考:

new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)

答案 3 :(得分:3)

function stringToDate(_date,_format,_delimiter)
{
        var formatLowerCase=_format.toLowerCase();
        var formatItems=formatLowerCase.split(_delimiter);
        var dateItems=_date.split(_delimiter);
        var monthIndex=formatItems.indexOf("mm");
        var dayIndex=formatItems.indexOf("dd");
        var yearIndex=formatItems.indexOf("yyyy");
        var month=parseInt(dateItems[monthIndex]);
        month-=1;
        var formatedDate = new Date(dateItems[yearIndex],month,dateItems[dayIndex]);
        return formatedDate;
}

stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")