Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert unix time to week day

How can I convert time from unix timestamp to week day? For example, I want to convert 1493193408 to Wednesday.

I tryed code above, but It always shows Sunday..

SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408);
String weekday = sdf.format(dateFormat );
like image 293
MrStuff88 Avatar asked Dec 08 '22 18:12

MrStuff88


2 Answers

Using java.time

The other Answers use the troublesome old date-time classes, now legacy, supplanted by the java.time classes.

Time zone is crucial in determining a date, and therefore getting a day-of-week.

Get an Instant from your count of while seconds since the epoch of 1970 in UTC. Apply a time zone to get a ZonedDateTime. From there extract a DayOfWeek enumerate object. Ask that object to automatically localize to generate a string of its name.

Instant.ofEpochSecond( 1_493_193_408L )
        .atZone( ZoneId.of( "America/Montreal" ))
        .getDayOfWeek()
        .getDisplayName( TextStyle.FULL , Locale.US )

For Android, see the ThreeTenABP project for a back-port of most of the java.time functionality.

like image 187
Basil Bourque Avatar answered Dec 10 '22 06:12

Basil Bourque


You need to multiply it by 1000 since Java and Unix time are not the same.

 SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408L * 1000);
String weekday = sdf.format(dateFormat );
like image 33
Alex Avatar answered Dec 10 '22 08:12

Alex