在Android中从时间戳获取日期名称

Sae*_*ani 2 java android timestamp date deprecated

我有一个类,在初始化时,它使用公共获取器在私有字段中记录初始化时间:

public class TestClass {

   private long mTimestamp;

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

    public long getTimestamp(){
          return mTimestamp;
    }
}
Run Code Online (Sandbox Code Playgroud)

我还有一个名为days的枚举:

public enum Days implements Serializable {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}
Run Code Online (Sandbox Code Playgroud)

现在问题出在另一个类中,我必须获取时间戳并将Days字段设置为该类初始化的日期:

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...
     }
}
Run Code Online (Sandbox Code Playgroud)

不推荐使用的getDay()方法Date...该怎么办?

JDJ*_*JDJ 6

如果您只需要以易于理解的格式将当前日期设置为当前用户的语言环境,则可以使用以下方法:

SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
String dayString = sdf.format(new Date());
Run Code Online (Sandbox Code Playgroud)

如果其语言环境为“ en_US”,则输出为:

Wednesday
Run Code Online (Sandbox Code Playgroud)

如果其语言环境为“ de_DE”,则输出为:

Mittwoch
Run Code Online (Sandbox Code Playgroud)

如果其区域设置为“ fr_FR”,则输出为:

mercredi
Run Code Online (Sandbox Code Playgroud)

但是,如果您需要数字表示星期几(例如,如果要在星期天获取“ 1”,在星期一则获取“ 2”),则可以使用日历:

Calendar cal = Calendar.getInstance();
int dayInt = cal.get(Calendar.DAY_OF_WEEK);
Run Code Online (Sandbox Code Playgroud)