After java Date is installed as English String it cannot be transferred back to Date's solution

  • 2020-05-27 05:31:49
  • OfStack

This is a problem for a colleague.

The Date in the code is put on the page in the format of "Fri Mar 21 09:20:38 CST 2014" (not shown, only passed to the next controller),

When the form is submitted again, private Date startTime of class Dto; Not entered by set.

One experiment was done with a local program


public static void main(String[] args) { 
  Date now = new Date(); 
  System.out.println(now); 
  String nowStr = now.toString(); 
  DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy"); 
  Date parsedNow = null; 
  try { 
    parsedNow = format.parse(nowStr); 
    System.out.println(parsedNow); 
  } catch (ParseException e) { 
    e.printStackTrace(); 
  } 
} 

Program execution format.parse (nowStr) times error

Java.text.ParseException: Unparseable date: "Fri Mar 21 09:25:48 CST 2014"

at java.text.DateFormat.parse(DateFormat.java:337)

Analyze and review the source code and conclude that the error was caused by the language used by the system.


DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy"); 

The default is


DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", new Locale(System.getProperty("user.language"))); 

Among them, System.getProperty (" user.language ") is zh because the system is in Chinese, so it should be the Chinese time zone does not support this kind of format.

Modify the code above to validate this view


public static void main(String[] args) { 
  Date now = new Date(); 
  System.out.println(now); 
  String nowStr = now.toString(); 
  DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", new Locale(System.getProperty("user.language"))); 
  System.out.println(System.getProperty("user.language")); 
  Date parsedNow = null; 
  try { 
    parsedNow = format.parse(nowStr); 
    System.out.println(parsedNow); 
  } catch (ParseException e) { 
    format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH); 
    try { 
      System.out.println("new format by 'en'"); 
      System.out.println(format.parse(nowStr)); 
    } catch (ParseException e1) { 
      e1.printStackTrace(); 
    } 
  } 
} 

Another solution is to convert the date format once on the jsp page, such as


<input type="hidden" name="data" value=' 
          <fmt:formatDate value="${dto.date}" pattern="yyyy-MM-dd"/> 
          '/> 

Related articles: