Android: 如何将字符串转换为日期?

190

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

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

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

有没有办法直接将这个字符串转换为Date对象?我想比较这个存储的时间和当前时间。


更新

谢谢大家。我使用了以下代码:

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;            
    
   }
7个回答

503

从字符串到日期

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();  
}

2
确切地说 - 最好在将日期字符串存储到数据库之前,对其应用一些标准格式。 在这种情况下,可以使用http://en.wikipedia.org/wiki/ISO_8601。 - denis.solonenko
为了更严格地解决“字符串转日期”的问题,在try...catch块之前添加“format.setLenient(false);”是很方便的。这样以前正确的字符串日期的检查会更好。 - Alecs
我不相信SimpleDateFormat.format()会抛出异常。 - Someone Somewhere
2
如果您的SDK版本大于或等于Marshmallow,则可以使用以下方式:SimpleDateFormat dateFormat =new SimpleDateFormat(""yyyy-MM-dd'T'HH:mm:ss'Z'"", Locale.getDefault()); - Dheeraj Jaiswal
我正在尝试将格式为dd/mm/Y的字符串转换为日期,但无论我选择什么日期进行转换,它都会返回27日,月份和年份正确返回。 - Viddyut Khanvilkar

19
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date d = dateFormat.parse(datestring)

2
不应该将字符串解析为变量吧?因为这样会尝试解析单词“string”。 - Marco

7
     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, 输出如下:

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

2018年3月14日


非常感谢! - Maryoomi1

6

通过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
}

3
您现在可以在Android中使用java.time,可以使用Android API Desugaring或导入ThreeTenAbp来实现。
启用java.time后,您可以使用更少的代码和更少的错误执行相同的操作。
假设您正在传递一个包含按ISO标准格式化的日期时间的String,就像当前接受的答案一样。然后,下面的方法及其在main中的用法可能会向您展示如何进行字符串转换:
public static void main(String[] args) {
    String dtStart = "2010-10-15T09:27:37Z";
    ZonedDateTime odt = convert(dtStart);
    System.out.println(odt);
}

and

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的偏移量。


1

在使用c.getTime().toString()时,小心依赖的Locale。

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


1
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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接