将Joda-Time日期时间格式化为字符串

问题描述 投票:1回答:4

我一直坚持将DateTime格式转换为String,我只是不知道如何正确地从此类型中仅获取Hours Minutes and Seconds。当我尝试自己的方式时,会得到类似2020-01-17T20:19:00的信息。但是我只需要得到20:19:00

import org.joda.time.DateTime; 

public DateTime orderDateFrom;
Log.d(TAG, orderDateFrom.toString());
java android time jodatime android-jodatime
4个回答
2
投票

尝试一下

SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
System.out.println(formatter.format(date));

2
投票
This will get time as 23:10:04 format

import java.text.SimpleDateFormat;
import java.util.Date;
import org.joda.time.DateTime;


        public DateTime orderDateFrom;

        Date d = orderDateFrom.toDate();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String formattedDate = sdf.format(d);

1
投票

由于您已经在使用Joda-Time,我建议您在两个选项之间进行选择:

  1. 现在与Joda-Time保持联系。
  2. 升级到java.time,现代Java日期和时间API以及Joda-Time的后继者。

我当然会全力劝阻的选项是从Java 1.0和1.1回到DateSimpleDateFOrmat。这些课程的设计很差,而且已经过时了,后者尤其出了名的麻烦。

与Joda-Time贴在一起

例如,如果您希望将DateTime中的时间格式化为String,以便输出给用户:

    DateTime orderDateFrom = new DateTime(2020, 1, 17, 20, 19, 0, DateTimeZone.forID("Mexico/BajaSur"));

    DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("HH:mm:ss");
    String formattedTime = orderDateFrom.toString(timeFormatter);
    System.out.println("Order time: " + formattedTime);

此代码段的输出是:

订购时间:20:19:00

如果希望将一天中的时间作为对象,可以将其用于进一步处理:

    LocalTime orderTime = orderDateFrom.toLocalTime();
    System.out.println("Order time: " + orderTime);

订购时间:20:19:00.000

我们注意到,由于no-arg toString方法执行了此操作,因此这次还打印了分钟的三位小数。您可以根据需要使用与上述相同的格式化程序对LocalTime进行格式化,以获取相同的字符串。

关于Android上的java.time的注释

[如果是针对Android API级别26和/或更高级别的编程,则内置java.time。如果需要考虑较低的API级别,则java.time是外部依赖项,就像Joda-Time:ThreeTenABP。这是JSR-310的ThreeTen(最初描述了java.time),而Android Backport的是ABP。请参阅底部的链接。

代码将是相似的,与上面使用Joda-Time的代码不同。

链接


0
投票

也许有更好的方法可以做到这一点,但您可以只获取子字符串。

String orderDateStr = orderDateFrom.toString();
orderDateStr.substring(orderDateStr.lastIndexOf("T")+1);
© www.soinside.com 2019 - 2024. All rights reserved.