簡體   English   中英

用Java解析字符串日期時間

[英]Parse String Date time in java

我有以下格式的日期時間(字符串): 2/19/2015 5:25:35 pm ,我想將日期時間設置為以下日期格式: Thu Feb 19 5:25:35 pm CET 2015我嘗試了以下代碼:

String sDatePrecedenteExecution  = "19/02/2015 17:30:29";
SimpleDateFormat format = new SimpleDateFormat ("ddd d mmm yyyy HH: mm: ss");
Date date = format.parse (sDatePrecedenteExecution)

但出現以下錯誤:

java.text.ParseException: unparseable Date: "2/19/2015 5:30:29 p.m."
Has java.text.DateFormat.parse (DateFormat.java:337)

您當前正在使用“輸出”格式來讀取傳入的日期字符串( 2/19/2015 5:25:35 pm ),這就是您看到錯誤的原因。

您需要指定第二種格式來解析傳入的日期字符串,並使用該格式來解析。 它看起來應該像這樣:

SimpleDateFormat inFormat = new SimpleDateFormat ("dd/MM/yyyy HH:mm:ss")
Date date = inFormat.parse(sDatePrecedenteExecution)

請注意,您的輸出格式中還存在一個錯誤m表示分鍾,而您想要MMM ,即幾個月。 看一下文檔。

您的SimpleDateFormat與您輸入的格式不匹配。 它們應該反映相同。

試試這個代碼

String parseDate = ""19/02/2015 17:30:29";

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date parsedDate = dateFormat.parse(parseDate);

您需要更改代碼,例如...

    String sDatePrecedenteExecution  = "19/02/2015 17:30:29";
    SimpleDateFormat format = new SimpleDateFormat ("dd/mm/yyyy HH:mm:ss");
    try {
        Date date = format.parse (sDatePrecedenteExecution);
        System.out.println(date);
        format = new SimpleDateFormat ("ddd d mmm yyyy HH: mm: ss");
        String str = format.format(date);
        System.out.println(str);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

試試這個模式:

SimpleDateFormat format = new SimpleDateFormat ("dd mm yyyy HH:mm:ss");

進行以下操作時出錯: "ddd d mmm yyyy HH: mm: ss"

請改用此格式“ dd / M / yyyy HH:mm:ss”並閱讀文檔

SimpleDateFormat format = new SimpleDateFormat ("dd/M/yyyy HH:mm:ss");
  String sDatePrecedenteExecution  = "19/02/2015 17:30:29";
 try{date =format.parse (sDatePrecedenteExecution);
      }catch(Exception ex){//deal with it here}
  System.out.println(date.toString()); //Thu Feb 19 17:30:29 UTC 2015

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM