0

I want to convert unix timestamp to only the current day, like the current day of the month of current day of the year, is it possible to do only using math, like *, /, or something?

Omega Cebbo
  • 17
  • 2
  • 7

3 Answers3

2

The short solution is something like

long epoch = 1501350790; // current unix time
int day = Integer.parseInt(new SimpleDateFormat("dd").format(new Date(epoch * 1000L)));

it is possible to get this result by calculation (* and /) but there is no easy way. you can use the implementation of java.util.GregorianCalendar as reference

Veli Örnek
  • 79
  • 1
  • 4
0

You can use SimpleDateFormat to format your date:

long unixSeconds = 1372339860;
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); // the format of your date
sdf.setTimeZone(TimeZone.getTimeZone("GMT-4")); // give a timezone reference for formating (see comment at the bottom
String formattedDate = sdf.format(date);
System.out.println(formattedDate);

You can also convert it to milliseconds by multiplying the timestamp by 1000:

java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);

After doing it, you can get what you want:

Calendar cal = Calendar.getInstance();
cal.setTime(dateTime);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH); //here is what you need
int day = cal.get(Calendar.DAY_OF_MONTH);
andreybleme
  • 689
  • 9
  • 23
0

You can calculate the date from a unix timestamp with java.util.Date You need to multiply the timestamp with 1000, because java expects milliseconds. You can use the cal.get(Calendar.DAY_OF_MONTH) function to print the day.

import java.sql.Timestamp;
import java.util.Calendar;

public class MyFirstJavaProgram {
    public static void main(String []args) {
       long unixTimeStamp= System.currentTimeMillis() / 1000L;
       java.util.Date time=new java.util.Date((long)unixTimeStamp*1000);
       Calendar cal = Calendar.getInstance();
       // It's a good point better use cal because date-functions are deprecated
       cal.setTime(time);
       System.out.println(cal.get(Calendar.DAY_OF_MONTH));
    }
}

Any further questions please leave a comment.

clfaster
  • 1,450
  • 19
  • 26
  • 1
    Or ideally *don't* use `java.util.Date` and `java.util.Calendar` - use the far, far better `java.time.*` API... – Jon Skeet Jul 29 '17 at 18:11