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?
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);
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With