Convert date with timezone

4

new Date () in javascript returns me this format:

  

Tue Apr 01 2014 13:43:13 GMT-0300 (BRT)

I need to convert this to a java.util.Date. For this I am trying to use SimpleDateFormat () but I did not find a pattern that worked, it always returns me:

  

java.text.ParseException: Unparseable date: "Tue Apr 01 2014 13:43:13 GMT-0300"

    
asked by anonymous 01.04.2014 / 18:51

3 answers

4

Since you already have the correct TimeZone ID, which in this case is BRT you could ignore the part that has GMT-0300 , because GMT in format can be problematic unless it is fixed. So I propose 2 solutions.

1) Removing GMT-0300

public static void main(String[] args) throws ParseException {
    String text = stripGMT("Tue Apr 01 2014 13:43:13 GMT-0300 (BRT)");
    String format = "EEE MMM dd yyyy HH:mm:ss  (zzz)";
    DateFormat dateFormat = new SimpleDateFormat(format);
    System.out.println(dateFormat.parse(text));
}

private static String stripGMT(String text) {
    return text.replaceAll("GMT-\d{4}", "");
}

2) Keeping GMT as a fixed argument

public static void main(String[] args) throws ParseException {
    String text = "Tue Apr 01 2014 13:43:13 GMT-0300 (BRT)";
    String format = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z (zzz)";
    DateFormat dateFormat = new SimpleDateFormat(format);
    System.out.println(dateFormat.parse(text));
}
    
01.04.2014 / 19:09
1

Set a String date pattern that Javascript must pass. After that, leave it to Java. A slightly more alternative way (if only) to do this would be to use the setTimeZone() method of DateFormat as follows:

DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
String strData = "30/05/2014 21:45";

try {
    Date data = df.parse(strData);
    System.out.println(data);
}
catch (ParseException e) {
    e.printStackTrace();
}

The output would be:

Fri May 30 18:45:00 BRT 2014

But you may wonder, what Timezones are available for use in the setTimeZone() method. You can list all TimeZones as follows:

for (String tz : TimeZone.getAvailableIDs()) {
    System.out.println(tz);
}

I will not post the output here, because it is a bit extensive. But I'm sure the timezone you're looking for will be on the list.

EDIT: Complementing the answer regarding Javascript. You can format object Date, using various methods like getMonth() , getDate() , getMinutes() ... This way you format the date as you want to send it to Java. See the full reference of the Date object in Javascript.

    
01.04.2014 / 19:18
0

As in English OS

  

The best way to convert is by using the time in milliseconds, UTC. Object Javascript Date and
  java.util.Date support conversion using milliseconds.

    
01.04.2014 / 18:55