【问题标题】:Convert Date and Time into a Single string Timestamp in seconds以秒为单位将日期和时间转换为单个字符串时间戳
【发布时间】:2020-10-24 19:11:37
【问题描述】:

我正在开发一个 Android 应用程序,它允许用户为计时器功能设置日期和时间。 我想以秒为单位将设置的日期和时间数据存储到单行时间戳中。 示例:

String datetime = Integer.toString(mDay) + Integer.toString(mMonth) + Integer.toString(mYear) + Integer.toString(mHour) + Integer.toString(mMinute);

日期时间的值为 11720202330 (11/7/2020 23:30) 我想将它存储为 s 中的时间戳值,即 Epoch 时间戳中的 1594510200。 谢谢。

【问题讨论】:

  • 您的日期时间String 的格式非常不合适...
  • 如果将 7 月 11 日指定为 11720202330(例如),那么 12 月 1 日将如何指定?我们可以将它与 2 月 11 日区别开来吗?那是字符串还是整数?

标签: java android android-studio datetime timestamp


【解决方案1】:

我们有一个以文本形式存储日期时间数据的标准:ISO 8601。无需发明新格式。

java.time 类在解析/生成字符串时默认使用标准格式。

LocalDate ld = LocalDate.of( year , month , day ) ;
LocalTime lt = LocalTime.of( hour , minute ) ;
ZoneId z = ZoneId.of( zoneName ) ;  // Ex: "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Instant instant = zdt.toInstant() ;
String output = instant.toString() ; 

解析 ISO 8601 字符串。

Instant instant = Instant.parse( "2020-07-12T03:30:00Z" ) ;

我建议不要将日期时间值存储为秒数或毫秒数。请改用 ISO 8601 字符串。但如果你坚持:

long secondsSinceEpoch = instant.getEpochSecond() ;

示例用法。 Run live at IdeOne.com.

int year = 2020 ;
int month = 7 ;
int day = 11 ;
int hour = 23 ;
int minute = 30 ;

zdt.toString(): 2020-07-11T23:30-04:00[美国/蒙特利尔]

instant.toString(): 2020-07-12T03:30:00Z

secondsSinceEpoch:1594524600

将2020-07-12T03:30:00Z 写入存储。

【讨论】:

  • 我还没有从你那里学到这么简单和有效的答案。
  • 我的 timepicker 和 datepicker 会产生这些变量: mHour mMinute mDay mMonth mYear 如上所示如何保存??
  • @BrianHeu 我添加了示例用法。
【解决方案2】:

测试一下

   String str_date = "11/7/2020 23:31";
    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm");
    Date date = (Date) formatter.parse(str_date);
    System.out.println("Today is " + date.getTime());

【讨论】:

  • 这些糟糕的日期时间类在几年前被 JSR 310 中定义的 java.time 类所取代。在 2020 年建议这些遗留类是糟糕的建议。
  • 这段代码忽略了时区的关键问题。结果可能在运行时有所不同。
  • 我认为日期完全不对。我刚刚将静态日期转换为 Unix 时间。
猜你喜欢
  • 1970-01-01
  • 2017-05-28
  • 1970-01-01
  • 1970-01-01
  • 2018-05-04
  • 2017-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多