【问题标题】:How to parse a string which holds date of format "Oct 1, 2015 12:00:00 AM"?如何解析包含“2015 年 10 月 1 日 12:00:00 AM”格式的日期的字符串?
【发布时间】:2015-10-30 04:38:37
【问题描述】:

什么格式可以将此 dateString 解析为Date?

String dateString = "Oct 1, 2015 12:00:00 AM";
try {
    SimpleDateFormat sdf = new SimpleDateFormat("");
    sdf.parse(dateString);              
} catch (ParseException e) {
    e.printStackTrace();
}

【问题讨论】:

  • 使用 MMM dd, yyyy hh:mm:ss a

标签: java android datetime


【解决方案1】:

SimpleDateFormat Javadoc 包含一个表,上面写着(部分)

Letter    Date or Time Component  Presentation    Examples
G         Era designator          Text            AD
y         Year                    Year            1996; 96
Y         Week year               Year            2009; 09
M         Month in year           Month           July; Jul; 07
w         Week in year            Number          27
W         Week in month           Number          2
D         Day in year             Number          189
d         Day in month            Number          10
F         Day of week in month    Number          2
E         Day name in week        Text            Tuesday; Tue
u         Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
a         Am/pm marker            Text            PM
H         Hour in day (0-23)      Number          0
k         Hour in day (1-24)      Number          24
K         Hour in am/pm (0-11)    Number          0
h         Hour in am/pm (1-12)    Number          12
m         Minute in hour          Number          30
s         Second in minute        Number          55
S         Millisecond             Number          978

我认为您需要像 MMM dd, yyyy hh:mm:ss a 这样的格式。类似的,

String userDateFormat = "MMM dd, yyyy hh:mm:ss a";
String dateString = "Oct 1, 2015 12:00:00 AM";
DateFormat sdf = new SimpleDateFormat(userDateFormat);
try {
    Date date = sdf.parse(dateString);
    System.out.println(sdf.format(date));
} catch (ParseException e) {
    e.printStackTrace();
}

哪些输出

Oct 01, 2015 12:00:00 AM

【讨论】:

  • 是否有任何 sqlite 查询来比较这样的日期,以便我可以将此日期与我的系统日期进行比较?
【解决方案2】:

可用于构建格式的Android reference for SimpleDateFormat has a table。

try {
    SimpleDateFormat sdf = new SimpleDateFormat("MMM,dd, yyyy hh:mm:s a");
    sdf.parse(dateString);

} catch (ParseException e) {
    e.printStackTrace();
}

【讨论】:

    【解决方案3】:

    这会起作用。

    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
    sdf.parse(dateString);
    

    【讨论】:

      【解决方案4】:

      如果您希望月份为 oct、jan 等,您可以使用它

      SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
      

      或者您可以使用月份数字

      SimpleDateFormat sdf = new SimpleDateFormat("MM dd, yyyy hh:mm:ss a");
      

      【讨论】:

        【解决方案5】:

        试试这个日期格式来转换日期字符串

        SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
        

        【讨论】:

          【解决方案6】:

          格式化和解析我们期望遇到的各种日期格式。

          import java.text.SimpleDateFormat;
          import java.util.Date;
          import java.util.Locale;
          import java.util.TimeZone;
          
          import android.util.Log;
          
          /**
           * Utility class for formatting and parsing the various date formats we expect
           * to encounter.
           */
          public class DateUtils{
            private static final String TAG = "DateUtils";
          
            private static final SimpleDateFormat[] dateFormats;
            private static final int dateFormat_default = 7;
          
            private DateUtils() { }
          
            static
            {
                final String[] possibleDateFormats =
                {
                  "EEE, dd MMM yyyy HH:mm:ss z", // RFC_822
                  "EEE, dd MMM yyyy HH:mm zzzz",
                  "yyyy-MM-dd'T'HH:mm:ssZ",
                  "yyyy-MM-dd'T'HH:mm:ss.SSSzzzz", // Blogger Atom feed has millisecs also
                  "yyyy-MM-dd'T'HH:mm:sszzzz",
                  "yyyy-MM-dd'T'HH:mm:ss z",
                  "yyyy-MM-dd'T'HH:mm:ssz", // ISO_8601
                  "yyyy-MM-dd'T'HH:mm:ss",
                  "yyyy-MM-dd'T'HHmmss.SSSz",
                  "yyyy-MM-dd"
                };
          
                dateFormats = new SimpleDateFormat[possibleDateFormats.length];
                TimeZone gmtTZ = TimeZone.getTimeZone("GMT");
          
                for (int i = 0; i < possibleDateFormats.length; i++)
                {
                  /* TODO: Support other locales? */
                  dateFormats[i] = new SimpleDateFormat(possibleDateFormats[i],
                    Locale.ENGLISH);
          
                  dateFormats[i].setTimeZone(gmtTZ);
                }
            }
          
            /**
             * Parse a date string.  The format of RSS/Atom dates come in many
             * different forms, so this method is extremely flexible and attempts to
             * understand many different formats.
             *
             * Copied verbatim from Informa 0.7.0-alpha2, ParserUtils.java.
             *
             * @param strdate
             *   Date string to attempt to parse.
             *
             * @return
             *   If successful, returns a {@link Date} object representing the parsed
             *   date; otherwise, null.
             */
            public static Date parseDate(String strdate)
            {
              Date result = null;
              strdate = strdate.trim();
              if (strdate.length() > 10) {
          
                // TODO deal with +4:00 (no zero before hour)
                if ((strdate.substring(strdate.length() - 5).indexOf("+") == 0 || strdate
                    .substring(strdate.length() - 5).indexOf("-") == 0)
                    && strdate.substring(strdate.length() - 5).indexOf(":") == 2) {
          
                  String sign = strdate.substring(strdate.length() - 5,
                      strdate.length() - 4);
          
                  strdate = strdate.substring(0, strdate.length() - 5) + sign + "0"
                  + strdate.substring(strdate.length() - 4);
                  // logger.debug("CASE1 : new date " + strdate + " ? "
                  //    + strdate.substring(0, strdate.length() - 5));
          
                }
          
                String dateEnd = strdate.substring(strdate.length() - 6);
          
                // try to deal with -05:00 or +02:00 at end of date
                // replace with -0500 or +0200
                if ((dateEnd.indexOf("-") == 0 || dateEnd.indexOf("+") == 0)
                    && dateEnd.indexOf(":") == 3) {
                  // TODO deal with GMT-00:03
                  if ("GMT".equals(strdate.substring(strdate.length() - 9, strdate
                      .length() - 6))) {
                    Log.d(TAG, "General time zone with offset, no change");
                  } else {
                    // continue treatment
                    String oldDate = strdate;
                    String newEnd = dateEnd.substring(0, 3) + dateEnd.substring(4);
                    strdate = oldDate.substring(0, oldDate.length() - 6) + newEnd;
                    // logger.debug("!!modifying string ->"+strdate);
                  }
                }
              }
              int i = 0;
              while (i < dateFormats.length) {
                try {
                  result = dateFormats[i].parse(strdate);
                  // logger.debug("******Parsing Success "+strdate+"->"+result+" with
                  // "+dateFormats[i].toPattern());
                  break;
                } catch (java.text.ParseException eA) {
                  i++;
                }
              }
          
              return result;
            }
          
            /**
             * Format a date in a manner that would be most suitable for serialized
             * storage.
             *
             * @param date
             *   {@link Date} object to format.
             *
             * @return
             *   Robust, formatted date string.
             */
            public static String formatDate(Date date)
            {
              return dateFormats[dateFormat_default].format(date);
            }
          }
          

          或者您可以使用以下函数解析日期..

           public static Date parseDate(String date, String format) throws ParseException {
                  if (date == null || date.length() == 0) {
                      return null;
                  }
                  SimpleDateFormat dateFormat = new SimpleDateFormat(format);
                  return dateFormat.parse(date);
              }
          

          希望对你有所帮助。

          【讨论】:

            【解决方案7】:
            Date and Time Pattern                       Result
            
            "yyyy.MM.dd G 'at' HH:mm:ss z"      2001.07.04 AD at 12:08:56 PDT
            
            "EEE, MMM d, ''yy"                  Wed, Jul 4, '01
            "h:mm a"                            12:08 PM
            "hh 'o''clock' a, zzzz"             12 o'clock PM,Pacific Daylight Time
            "K:mm a, z"                         0:08 PM, PDT
            "yyyyy.MMMMM.dd GGG hh:mm aaa"      02001.July.04 AD 12:08 PM
            "EEE, d MMM yyyy HH:mm:ss Z"        Wed, 4 Jul 2001 12:08:56 -0700
            "yyMMddHHmmssZ"                     010704120856-0700
            "yyyy-MM-dd'T'HH:mm:ss.SSSZ"        2001-07-04T12:08:56.235-0700
            "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"      2001-07-04T12:08:56.235-07:00
            "YYYY-'W'ww-u"                      2001-W27-3
            

            然后你可以像下面这样转换你的日期字符串,

            String dateString="Oct 1, 2015 12:00:00 AM";
            
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("MMM,dd, yyyy hh:mm:s a");
                sdf.parse(dateString);
            
            } catch (ParseException e) {
                e.printStackTrace();
            }
            

            【讨论】:

              猜你喜欢
              • 2023-01-13
              • 2020-12-03
              • 2016-01-24
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-03-25
              • 2014-04-26
              相关资源
              最近更新 更多