将 Java 日期字符串转换为 javascript 日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4679638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert Java datestring to javascript date
提问by orshachar
When I send a date through JSON from Java to Javascript, it sends something like this:
当我通过 JSON 从 Java 向 Javascript 发送日期时,它会发送如下内容:
var ds = "11:07:47 13/01/2011";
Javascript fails to parse this string into date
Javascript 无法将此字符串解析为日期
var d = new Date(ds);
Any ideas?
有任何想法吗?
回答by sebarmeli
You need some JS that parse the String and return the year, month, day, minute,hour, second in strings:
您需要一些 JS 来解析字符串并返回字符串中的年、月、日、分钟、小时、秒:
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];
and then instantiate the Date constructor:
然后实例化 Date 构造函数:
var d = new Date ( year, month, day, hour, minute, second );
回答by sjngm
To be on the safe side you should get the time in milliseconds in Java and send that through JSON to JavaScript. There you can use
为了安全起见,您应该在 Java 中获取以毫秒为单位的时间,并通过 JSON 将其发送到 JavaScript。在那里你可以使用
var d = new Date();
d.setTime(valueInMilliseconds);
回答by wosis
There are a number of ways you can call the Date
constructor.
From the reference at http://www.w3schools.com/js/js_obj_date.asp:
您可以通过多种方式调用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)
回答by Kassem
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","-")