簡體   English   中英

如何將字符串轉換為日期?

[英]How to convert a string to a Date?

我不知道格式字符串是什么

可能是2015-10-102015/10/10 ,也可能是2015-10-30 15:30

定期首先我想用來判斷一個有效的日期或時間,然后使用SimpleDateFormat解析,我該怎么辦?

所有格式包括:

- yyyy-MM-dd
- yyyy.MM-dd
- yyyy/MM/dd
- yyyy-MM-dd HH24:mm
- yyyy.MM-dd HH24:mm
- yyyy/MM/dd HH24:mm
- yyyy-MM-dd HH24:mm:ss
- yyyy.MM-dd HH24:mm:ss
- yyyy/MM/dd HH24:mm:ss
use following date formatter to convert the date to String.
String d="2015-05-12";
DateFormat formatter  = new SimpleDateFormat("yyyy-mm-dd");
Date a=formatter.parse(d);

我已經使用了Natty Date Parser 你可以在這里試試。 它可用於Maven的中央位置 如果您使用的是gradle:

compile 'com.joestelmach:natty:0.12'

用法示例:

String[] exampleDates = {
    "2015-10-10",
    "2015/10/10",
    "2015-10-30 15:30"
};

Parser parser = new Parser();
for (String dateString : exampleDates) {
  List<DateGroup> dates = parser.parse(dateString);
  Date date = dates.get(0).getDates().get(0);
  System.out.println(date);
}

輸出:

10月10日星期六20:51:10 PDT 2015

10月10日星期六20:51:10 PDT 2015

10月30日星期五15:30:00 PDT 2015


編輯:

如果您知道日期格式,那么以下StackOverflow將比向項目添加依賴項更好:

https://stackoverflow.com/a/4024604/1048340


以下靜態實用程序方法可能就足夠了:

/**
 * Parses a date with the given formats. If the date could not be parsed then {@code null} is
 * returned.
 *
 * @param formats the possible date formats
 * @param dateString the date string to parse
 * @return the {@link java.util.Date} or {@code null} if the string could not be parsed.
 */
public static Date getDate(String[] formats, String dateString) {
  for (String format : formats) {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    try {
      return sdf.parse(dateString);
    } catch (ParseException ignored) {
    }
  }
  return null;
}

暫無
暫無

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

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