如何使用 SimpleDateFormat.parse() 将 Calendar.toString() 转换为日期?

How can I Convert Calendar.toString() into date using SimpleDateFormat.parse()?

我正在开发一个使用数据库的 Android 应用程序,每次用户插入新寄存器时,当前数据和时间都会使用

保存在数据库中
Calendar cal = Calendar.getInstance();

所以,当我从数据库中检索数据时,得到了这样一个字符串:

java.util.GregorianCalendar[time=1496007575129,areFieldsSet=true,lenient=true,zone=America/Mexico_City,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2017,MONTH=4,WEEK_OF_YEAR=22,WEEK_OF_MONTH=5,DAY_OF_MONTH=28,DAY_OF_YEAR=148,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=39,SECOND=35,MILLISECOND=129,ZONE_OFFSET=-21600000,DST_OFFSET=3600000]

当我尝试使用 SimpleDateFormat.parse 转换该字符串以在 RecyclerView 中显示它时出现问题,我总是得到相同的日期:09/04/2017。

这是我的代码 RecViewAdapter.java:

@Override
public void onBindViewHolder(ViewHolder holder,int position){
    items.moveToPosition(position);

    String s,d,p,f;


    s = items.getString(ConsultaTomas.SISTOLICA);
    holder.systolica.setText(s);

    d = items.getString(ConsultaTomas.DIASTOLICA);
    holder.diastolica.setText(d);

    p = items.getString(ConsultaTomas.PULSO);
    holder.pulso.setText(p);

    f = items.getString(ConsultaTomas.FECHA);
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    try {
        holder.fecha.setText(sdf.format(sdf.parse(f)));

    }catch (ParseException e){
        Log.d("PARSINGFECHA","Error al parcear fecha");
    }


}

RecView 中正确显示的其他数据和日历字符串都不同,因此这些字符串中不相同 date/hour。所以,问题是:

如何使用 SimpleDateFormat.parse()Calendar.toString() 转换为日期?

这是 运行 应用程序在真实设备中的结果:

您需要修改存储 Calendar 的方式,调用 getTime() 并根据需要格式化它。例如,

Calendar cal = Calendar.getInstance();
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
System.out.println(sdf.format(cal.getTime()));

tl;博士

( GregorianCalendar ) myCal                    // Cast the more general `Calendar` to subclass `GregorianCalendar`. 
.toZonedDateTime()                             // Convert from terrible legacy class `GregorianCalendar` to its modern replacement `ZonedDateTime`. 
.toLocalDate()                                 // Extract just the date, without the time-of-day and without the time zone. Returns a `LocalDate` object.
.format(                                       // Generate text representing the value of this `LocalDate` object.
    DateTimeFormatter
    .ofLocalizedDate( FormatStyle.SHORT )      // Automatically localize the text.
    .withLocale( new Locale( "es" , "ES" ) )   // Specify a `Locale` to determine the human language and cultural norms to use in localization.
)

java.time

现代方法使用 java.time 类 多年前取代了可怕的遗产 类 Calendar & GregorianCalendar

当您遇到 Calendar 对象时,立即转换为它的替换 ZonedDateTime,假设您的对象实际上是 GregorianCalendar.

if( myCal instanceOf GregorianCalendar )
{
    GregorianCalendar gc = ( GregorianCalendar ) myCal ;  // Cast from more general class to the specific class.
    ZonedDateTime zdt = gc.toZonedDateTime() ;
}

您显然只对日期部分感兴趣,没有时间和时区。所以提取一个LocalDate.

LocalDate ld = zdt.toLocalDate() ;  // Ignore time-of-day and time zone.

以您想要的格式生成文本。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
String output = ld.format( f ) ;

或者更好:让 java.time 自动为您本地化。

Locale locale = new Locale( "es" , "ES" ) ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( locale ) ;

关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

Joda-Time project, now in maintenance mode, advises migration to the java.time 类.

您可以直接与数据库交换 java.time 对象。使用 JDBC driver compliant with JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* 类。 Hibernate 5 和 JPA 2.2 支持 java.time

java.time类在哪里获取?