convert Java datestring to javascript date [duplicate]
Asked Answered
W

4

11

When I send a date through JSON from Java to Javascript, it sends something like this:

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

Javascript fails to parse this string into date

var d = new Date(ds);

Any ideas?

Womanhater answered 13/1, 2011 at 11:40 Comment(2)
Tthis was asked on January 2011, dup link is April 2011, how can this be a duplicate ?Fortin
The “duplicate” is closed for being unclear what is asked. Time to reopen this question.Martinsen
P
17

You need some JS that parse the String and return the year, month, day, minute,hour, second in strings:

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:

var d = new Date ( year, month, day, hour, minute, second );
Privilege answered 13/1, 2011 at 11:49 Comment(3)
Line 3 should be second = ds.split(":")[2],, delete 4th line, 5th line should be last_part2 = ds.split(" ")[1],. You could rename last_part2 as it isn't the 2nd one anymore.Assuming
thanks for writing the code , it worked like a charm!Womanhater
An alternate approach would be to use moment.js to get a Date object: var d = moment(ds, "HH:mm:ss DD/MM/YYYY").asDate(); The second string is the format to use for parsing the input date String.Vidavidal
V
5

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

var d = new Date();
d.setTime(valueInMilliseconds);
Vituline answered 13/1, 2011 at 11:51 Comment(0)
A
4

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:

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)
Ameliaamelie answered 13/1, 2011 at 12:13 Comment(0)
M
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","-")
Mudstone answered 21/9, 2014 at 17:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.