从Android的时间戳获得天的名称 [英] Get name of day from timestamp in Android

查看:186
本文介绍了从Android的时间戳获得天的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,它的初始化时,它记录初始化的时间在私人领域与公共的getter:

I have a class that when its initialized, it records the time of initialization in a private field with a public getter:

public class TestClass {

   private long mTimestamp;

    public TestClass(){
      mTimestamp = System.getCurrentMillis();
    }

    public long getTimestamp(){
          return mTimestamp;
    }
}

我也有天的名称的枚举:

I also have an enum with the name of days:

public enum Days implements Serializable {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}

现在的问题是另一个类我一定要得到的时间戳和字段设置为一天,类初始化:

Now the problem is in another class I have to get the timestamp and set a Days field to the day that the class was initialized:

public class OtherClass {

     public Days getDayOfInitialization(TestClass testClass){
          //how to do this?
          Date date = new Date(testClass.getTimestamp())
          Days day = Date.getDay(); //Deprecated!
          //convert to enum and return...
     }
}

日期 getDay()法德precated ......我应该怎么做?

The getDay() method of Date is deprecated...how should I do this?

推荐答案

您不需要那么枚举为日期时间标准( ISO 8601 )一个星期定义为周一至周日。

Standard Week

You do not need that Enum as the standard for date-time (ISO 8601) defines a week as Monday to Sunday.

乔达时的英文定义了一天的周每个名称常量如的 DateTimeConstants.MONDAY

Joda-Time defines constants for each day-of-week name in English such as DateTimeConstants.MONDAY.

您应该使用乔达时库,作为Java .util.Date和.Calendar类是出了名的麻烦。乔达时根据人的作品在Android中。

You should be using Joda-Time library, as the java.util.Date and .Calendar classes are notoriously troublesome. Joda-Time works in Android according to others.

追踪日期时间以毫秒为单位是达不到最佳。序列化到ISO 8601字符串是preferable。但是,如果你一定要,就这样吧。

Tracking date-time as milliseconds is less than optimal. Serializing to a ISO 8601 string is preferable. But if you must, so be it.

时区是至关重要的。一天的周由时区的定义,如以上所讨论的评论

Time zone is crucial. Day-of-week is defined by time zone, as the comments above discussed.

如果你想 UTC ,乔达时提供恒定的 DateTimeZone.UTC

If you want UTC, Joda-Time provides the constant DateTimeZone.UTC.

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime = new DateTime( millisSinceEpochInUtc, timeZone );
int dayOfWeekNumber = dateTime.getDayOfWeek(); // ISO 8601 standard says Monday is 1.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEEE" ).withLocale( java.util.Locale.ENGLISH );
String dayOfWeekName = formatter.print( dateTime );

这篇关于从Android的时间戳获得天的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆