Skip to content Skip to sidebar Skip to footer

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 sd

Solution 1:

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.

Solution 2:

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

SimpleDateFormatsdf=newSimpleDateFormat("EEEE");
DatedateFormat=newjava.util.Date(1493193408L * 1000);
Stringweekday= sdf.format(dateFormat );

Solution 3:

You can use a calendar instance because it provides you methods for getting that information:

Datedate = newDate(1493193408000L);
Calendar c = Calendar.getInstance();
c.setTime(date);

System.out.println(c.get(Calendar.DAY_OF_WEEK));
System.out.println(c.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US));

Solution 4:

The Date constructor has the following description:

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

Your timestamp is in seconds, if you multiply by 1000 (to get milliseconds) you get the expected answer:

SimpleDateFormatsdf=newSimpleDateFormat("EEEE");
 DatedateFormat=newjava.util.Date(1493193408000L);
 System.out.println(dateFormat);
 Stringweekday= sdf.format(dateFormat);
 System.out.println(weekday);

Which prints

WedApr2609:56:48CEST2017Wednesday

Solution 5:

dateFormatStart != dateFormat

You could also check using:

SimpleDateFormatsdf=newSimpleDateFormat("EEEE");
DatedateFormat=newDate(System.currentTimeMillis());
Stringweekday= sdf.format(dateFormat);

Post a Comment for "Convert Unix Time To Week Day"