【问题标题】:How can I Convert Calendar.toString() into date using SimpleDateFormat.parse()?如何使用 SimpleDateFormat.parse() 将 Calendar.toString() 转换为日期?
【发布时间】:2017-11-05 18:36:37
【问题描述】:

我正在开发一个使用数据库的 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 中正确显示并且日历字符串都不同,因此这些字符串中的日期/小时不一样。所以,问题是:

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

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

【问题讨论】:

    标签: java android calendar simpledateformat


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的解决方案,我实际上将 cal.getTime() 值保存在 bd 中,并将这些值转换为在适配器中进行查询时的日期。
    【解决方案2】:

    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 类,它在几年前取代了可怕的遗留类 CalendarGregorianCalendar

    当您遇到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 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

    要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

    Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

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

    从哪里获得 java.time 类?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-04
      • 2022-07-06
      • 2017-04-15
      • 2011-04-14
      • 2010-11-03
      • 2020-03-19
      相关资源
      最近更新 更多