【问题标题】:Android: How can I Convert String to Date?Android:如何将字符串转换为日期?
【发布时间】:2012-01-24 06:53:03
【问题描述】:

每次用户启动应用程序时,我都会将当前时间存储在数据库中。

Calendar c = Calendar.getInstance();
    String str = c.getTime().toString();
    Log.i("Current time", str);

在数据库端,我将当前时间存储为字符串(如您在上面的代码中所见)。因此,当我从数据库加载它时,我需要将它转换为 Date 对象。我看到了一些样本,他们都使用了“DateFormat”。但我的格式与日期格式完全相同。所以,我认为没有必要使用“DateFormat”。我说的对吗?

是否可以直接将此字符串转换为日期对象?我想将此存储的时间与当前时间进行比较。

谢谢

======> 更新

谢谢亲爱的朋友们。我使用了以下代码:

private boolean isPackageExpired(String date){
        boolean isExpired=false;
        Date expiredDate = stringToDate(date, "EEE MMM d HH:mm:ss zz yyyy");        
        if (new Date().after(expiredDate)) isExpired=true;

        return isExpired;
    }

    private Date stringToDate(String aDate,String aFormat) {

      if(aDate==null) return null;
      ParsePosition pos = new ParsePosition(0);
      SimpleDateFormat simpledateformat = new SimpleDateFormat(aFormat);
      Date stringDate = simpledateformat.parse(aDate, pos);
      return stringDate;            

   }

【问题讨论】:

    标签: android string date casting


    【解决方案1】:
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    Date d = dateFormat.parse(datestring)
    

    【讨论】:

    • 不应该将String解析为变量吗?因为这样,它试图解析单词“string”。
    【解决方案2】:

    从字符串到日期

    String dtStart = "2010-10-15T09:27:37Z";  
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
    try {  
        Date date = format.parse(dtStart);  
        System.out.println(date);  
    } catch (ParseException e) {
        e.printStackTrace();  
    }
    

    从日期到字符串

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
    try {  
        Date date = new Date();  
        String dateTime = dateFormat.format(date);
        System.out.println("Current Date Time : " + dateTime); 
    } catch (ParseException e) {
        e.printStackTrace();  
    }
    

    【讨论】:

    • 完全正确 - 最好在将日期字符串存储到数据库之前对其应用一些标准形式。在这种情况下en.wikipedia.org/wiki/ISO_8601
    • 对于“string to date”更严格的工作解决方案,添加“format.setLenient(false);”很方便在 try...catch 块之前。这样可以更好地检查以前正确的字符串日期。
    • 我不相信SimpleDateFormat.format() 会抛出异常
    • 如果您的 SDK 版本大于或等于 Marshmallow 则像这样使用SimpleDateFormat dateFormat =new SimpleDateFormat(""yyyy-MM-dd'T'HH:mm:ss'Z'"", Locale.getDefault());
    • 我正在尝试将 dd/mm/Y 格式的字符串转换为日期,但是当我转换时,无论我选择什么日期,它都会返回日期为 27,正确返回月份和年份。
    【解决方案3】:

    通过使用 SimpleDateFormat 或 DateFormat 类

    例如

    try{
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
    Date d = sdf.parse("20/12/2011");
    }catch(ParseException ex){
        // handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
    }
    

    【讨论】:

      【解决方案4】:

      注意c.getTime().toString(); 所依赖的语言环境可能是个好主意。

      一个想法是以秒为单位存储时间(例如UNIX time)。作为int,您可以轻松比较它,然后在向用户显示时将其转换为字符串。

      【讨论】:

        【解决方案5】:
        String source = "24/10/17";
        
        String[] sourceSplit= source.split("/");
        
        int anno= Integer.parseInt(sourceSplit[2]);
        int mese= Integer.parseInt(sourceSplit[1]);
        int giorno= Integer.parseInt(sourceSplit[0]);
        
            GregorianCalendar calendar = new GregorianCalendar();
          calendar.set(anno,mese-1,giorno);
          Date   data1= calendar.getTime();
          SimpleDateFormat myFormat = new SimpleDateFormat("20yy-MM-dd");
        
            String   dayFormatted= myFormat.format(data1);
        
            System.out.println("data formattata,-->"+dayFormatted);
        

        【讨论】:

          【解决方案6】:
               import java.text.ParseException;
               import java.text.SimpleDateFormat;
               import java.util.Date;
               public class MyClass 
               {
               public static void main(String args[]) 
               {
               SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
          
               String dateInString = "Wed Mar 14 15:30:00 EET 2018";
          
               SimpleDateFormat formatterOut = new SimpleDateFormat("dd MMM yyyy");
          
          
               try {
          
                  Date date = formatter.parse(dateInString);
                  System.out.println(date);
                  System.out.println(formatterOut.format(date));
          
                   } catch (ParseException e) {
                  e.printStackTrace();
                   }
              }
              }
          

          这是你的 Date 对象 date 输出是:

          2018 年 3 月 14 日星期三 13:30:00 UTC

          2018 年 3 月 14 日

          【讨论】:

          • 非常感谢!
          【解决方案7】:

          您现在可以在 Android 中使用 java.time,方法是使用 Android API Desugaring 或导入 ThreeTenAbp

          启用java.time 后,您可以用更少的代码和更少的错误执行相同的操作。

          假设您传递了一个String,其中包含以 ISO 标准格式化的日期时间,就像当前接受的答案一样。
          那么main 中的以下方法及其用法可能会向您展示如何从String 转换为String

          public static void main(String[] args) {
              String dtStart = "2010-10-15T09:27:37Z";
              ZonedDateTime odt = convert(dtStart);
              System.out.println(odt);
          }
          

          public static void main(String[] args) {
              String dtStart = "2010-10-15T09:27:37Z";
              OffsetDateTime odt = convert(dtStart);
              System.out.println(odt);
          }
          

          将打印该行

          2010-10-15T09:27:37Z
          

          当有相应的方法时

          public static OffsetDateTime convert(String datetime) {
              return OffsetDateTime.parse(datetime);
          }
          

          public static ZonedDateTime convert(String datetime) {
              return ZonedDateTime.parse(datetime);
          }
          

          但当然不在同一个类中,那不会编译...

          还有一个LocalDateTime,但它无法解析区域或偏移量。

          如果您想使用自定义格式来解析或格式化输出,您可以使用DateTimeFormatter,可能是这样的:

          public static void main(String[] args) {
              String dtStart = "2010-10-15T09:27:37Z";
              String converted = ZonedDateTime.parse(dtStart)
                                              .format(DateTimeFormatter.ofPattern(
                                                              "EEE MMM d HH:mm:ss zz uuuu",
                                                              Locale.ENGLISH
                                                          )
                                                      );
              System.out.println(converted);
          }
          

          哪个会输出

          Fri Oct 15 09:27:37 Z 2010
          

          对于OffsetDateTime,您需要稍微调整一下模式:

          public static void main(String[] args) {
              String dtStart = "2010-10-15T09:27:37Z";
              String converted = OffsetDateTime.parse(dtStart)
                                              .format(DateTimeFormatter.ofPattern(
                                                              "EEE MMM d HH:mm:ss xxx uuuu",
                                                              Locale.ENGLISH
                                                          )
                                                      );
              System.out.println(converted);
          }
          

          这将产生(稍微)不同的输出:

          Fri Oct 15 09:27:37 +00:00 2010
          

          这是因为ZonedDateTime 认为命名时区具有不断变化的偏移量(由于夏令时或类似情况),而OffsetDateTime 只是知道与 UTC 的偏移量。

          【讨论】:

            猜你喜欢
            • 2018-12-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-05-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多