Java SimpleDateFormat Pattern for JavaScript Date

前端 未结 4 1641
时光说笑
时光说笑 2020-12-07 03:04

I need to convert a Java Date object to a string that is the same format as JavaScript Dates when they are converted to a string. On our server we have JavaScript dates that

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 03:48

    To format the date exactly like that, we may need to format date and timezone separately, e,g,:

    SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy hh:mm:ss");
    Date date = new Date();
    String dateStr = format.format(date);
    TimeZone tz = TimeZone.getDefault();
    int offset = tz.getRawOffset();
    
    String text = String.format("%s%02d%02d", offset >= 0 ? "+" : "-", offset / 3600000, (offset / 60000) % 60);
    
    String timeZoneText = "GMT" + text + " (" + tz.getDisplayName(true, tz.SHORT, Locale.getDefault())+")";
    
    System.out.println(dateStr + " " + timeZoneText);
    

提交回复
热议问题