Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name of day from timestamp in Android

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...
     }
}

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

like image 435
Saeid Yazdani Avatar asked Dec 02 '22 16:12

Saeid Yazdani


2 Answers

If you just need the current day of week in a human-readable format, formatted to the current user's locale, then you could use this:

SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
String dayString = sdf.format(new Date());

If their locale is "en_US", the output is:

Wednesday

If their locale is "de_DE", the output is:

Mittwoch

If their locale is "fr_FR", the output is:

mercredi

But if you need a numerical representation of the day of week (for example, you wanted to get '1' if it is Sunday or '2' if it is Monday), then you could use Calendar:

Calendar cal = Calendar.getInstance();
int dayInt = cal.get(Calendar.DAY_OF_WEEK);
like image 189
JDJ Avatar answered Dec 04 '22 04:12

JDJ


use Calendar:

  long timeStamp = testClass.getTimestamp();
  Calendar c = Calendar.getInstance();
  c.setTimeInMillis(timeStamp);

  int dayNum = c.get(Calendar.DAY_OF_WEEK);

  Days day = Days.values()[dayNum];

  return day;
like image 38
mrd abd Avatar answered Dec 04 '22 04:12

mrd abd