首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用SimpleDateFormat.parse()将Calendar.toString()转换为date?

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

Stack Overflow用户
提问于 2017-06-05 11:31:09
回答 2查看 4.6K关注 0票数 1

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

代码语言:javascript
复制
Calendar cal = Calendar.getInstance();

因此,当我从数据库中检索数据时,得到了如下字符串:

区域偏移量,lenient=true,区域=美国/墨西哥城,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,ZONE_OFFSET=-21600000,

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

这是我的RecViewAdapter.java中的代码:

代码语言:javascript
复制
@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()转换为日期

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-06-05 11:33:56

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

代码语言:javascript
复制
Calendar cal = Calendar.getInstance();
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
System.out.println(sdf.format(cal.getTime()));
票数 5
EN

Stack Overflow用户

发布于 2020-05-28 09:18:38

tl;dr

代码语言:javascript
复制
( 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

现代方法使用多年前取代了糟糕的遗留类Calendar & GregorianCalendar的java.time类。

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

代码语言:javascript
复制
if( myCal instanceOf GregorianCalendar )
{
    GregorianCalendar gc = ( GregorianCalendar ) myCal ;  // Cast from more general class to the specific class.
    ZonedDateTime zdt = gc.toZonedDateTime() ;
}

显然,您只对日期部分感兴趣,而不关心时间和时区。因此,提取一个LocalDate

代码语言:javascript
复制
LocalDate ld = zdt.toLocalDate() ;  // Ignore time-of-day and time zone.

生成所需格式的文本。

代码语言:javascript
复制
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
String output = ld.format( f ) ;

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

代码语言:javascript
复制
Locale locale = new Locale( "es" , "ES" ) ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( locale ) ;

关于java.time

框架内置于Java8和更高版本中。这些类取代了麻烦的旧legacy日期时间类,如java.util.DateCalendarSimpleDateFormat

要了解更多信息,请参阅。和搜索堆栈溢出,以获得许多示例和解释。规范为JSR 310

现在在maintenance mode中的项目建议迁移到java.time类。

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

从哪里获取java.time类?

  • ,、、和更高版本-标准Java API的一部分,具有捆绑的实现。
    • Java9添加了一些次要功能和fixes.

  • 和.

中的

  • 大多数java.time功能已向后移植到Java6和7

    • 更高版本的Android捆绑实现的java.time类。
    • 对于较早的Android (<26),项目适配 (如上所述)。请参阅.

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44361292

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档