How to Convert JavaScript Date to Date in Java?

前端 未结 6 1292
暗喜
暗喜 2020-12-08 13:19

I need to convert JsDate to java.util.Date. I searched but I couldn\'t find anything. So could you help me with this problem?

Edit:

相关标签:
6条回答
  • 2020-12-08 13:38

    The best way of dates conversion is using time in milliseconds, UTC. Both JS Date object and java.util.Date class support conversion to milliseconds (getTime()) and instantiating from milliseconds (using constructor).

    0 讨论(0)
  • 2020-12-08 13:53

    You may want this:

    java:
    String jsDate="2013-3-22 10:13:00";
    Date javaDate=new SimpleDateFormat("yy-MM-dd HH:mm:ss").parse(jsDate);
    System.out.println(javaDate);
    
    0 讨论(0)
  • 2020-12-08 13:55

    I would suggest using the DateFormat parse method (doc can be found here). It can parse a string representation of a date and return a java.util.Date.

    0 讨论(0)
  • 2020-12-08 13:59

    JS Date -- new Date() Wed Aug 14 2019 14:54:38 GMT+0530 (India Standard Time)

    Java Date -- new Date().toISOString() "2019-08-14T09:25:50.136Z"

    0 讨论(0)
  • 2020-12-08 14:02

    You can create a java.util.Date object from the 'time since epoch' value of the JS Date

    javascript

    var d = new Date().getTime();
    

    java

    // get value from client (ajax, form, etc), and construct in Date object
    
    long valueFromClient = ...
    
    Date date = new Date(valueFromClient);
    
    String formatted = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
    
    0 讨论(0)
  • 2020-12-08 14:03

    If people like me are forced to parse a JS-formatted date string (as the result of (new Date()).toString() in JavaScript), here is the SimpleDateFormat spec I used:

    DateFormat jsfmt = new SimpleDateFormat("EE MMM d y H:m:s 'GMT'Z (zz)");
    

    If you have control of the producer of the dates, I concur that using timestamps or at least .toUTCString() is definitely more robust.

    0 讨论(0)
提交回复
热议问题