【问题标题】:Android Time class - Milliseconds back to Time?Android 时间类 - 回到时间的毫秒数?
【发布时间】:2013-08-13 23:27:13
【问题描述】:

这就是我所拥有的......如果我将它转换为毫秒,我必须将它存储很长时间。我使用 Android API 时间类 (http://developer.android.com/reference/android/text/format/Time.html)

Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
long todayMillis = today.toMillis(false);

我想在类似这样的可读版本之后将其格式化(在获得 teh 毫秒后,我将其保存到数据库中以便之后检索它):

todayMillis.format("%k:%M %d.%m.%y");

但我不能那么容易地做到这一点,因为我需要转换回时间.. 怎么做?

【问题讨论】:

  • 你想把它转换成字符串还是转换回 Time 类?
  • 基本上我想把它显示为一个字符串,但我想我必须把它恢复到 Time 才能格式化它?

标签: java android date time


【解决方案1】:

新建一个时间对象,然后调用Time.set(long milliseconds)

Time time = new Time(Time.getCurrentTimeZone());
time.set(todayMillis);

我认为甚至不需要原始时区,因为毫秒是 UTC,但我猜 Time 对象在内部以某种方式使用传递的时区。

【讨论】:

  • 你确实是对的......谢谢你,不知道我自己是怎么没有从手册中读到的!!!
  • 呃,这个东西很容易被忽视。特别是如果你整天盯着屏幕看!
【解决方案2】:

您已经拥有Time 类型的today 对象,因此无需将毫秒转换回时间。但如果必须,android.text.format.Time 包含一个 set 方法,它将 milliseconds 作为 long

Time newToday = new Time();
newToday.set(todayMillis);
newToday.format("%k:%M %d.%m.%y");

Documentation

【讨论】:

  • 对不起,我忘了提到我保存到数据库,所以我晚了几毫秒才检索它... 然后想格式化它。
【解决方案3】:

试试这个:

Calendar calendar = Calendar.getInstance(); // Creates a new Calendar with the current Time
calendar.setTimeInMillis(todaysMillis);  // you can also put your millis in. Same effect.
String readableOutput = calendar.get(Calendar.HOUR_OF_DAY) +
            ":" + calendar.get(Calendar.MINUTE) +
            " " + calendar.get(Calendar.DAY_OF_MONTH) +
            "." + (1+calendar.get(Calendar.MONTH)) +
            "." + calendar.get(Calendar.YEAR);

更多字段和方法: http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

【讨论】:

    猜你喜欢
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2013-02-22
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    相关资源
    最近更新 更多