0

I convert current time to the integer formats using this code

 long x1=new Date().getTime();
 int x=(int) x1;

Now I want get the actual date values separately(Year,Month,Date,Hour,Minute) from the integer int x.

How can I do that?

Thank You(Please Guide me)

Hearen
  • 7,420
  • 4
  • 53
  • 63

2 Answers2

3

With java 8, you can easily manage that in LocalDate

    LocalDate today = LocalDate.now();
    int thisYear = today.getYear();
    int thisMonth = today.getMonthValue();
    int thisDay = today.getDayOfMonth();
    out.println(thisYear + "-" + thisMonth + "-" + thisDay);

But when you try to achieve more (hours, minutes, seconds), you then can turn to LocalDateTime

    LocalDateTime curMoment = LocalDateTime.now();
    thisYear = curMoment.getYear();
    thisMonth = curMoment.getMonthValue();
    thisDay = curMoment.getDayOfMonth();
    int thisHour = curMoment.getHour();
    int thisMinute = curMoment.getMinute();
    int thisSecond = curMoment.getSecond();
    System.out.println(thisYear + "-" + thisMonth + "-" + thisDay + " " + thisHour + ":" + thisMinute + ":" + thisSecond);

And then the output will be:+

2018-7-4
2018-7-4 14:33:12
Hearen
  • 7,420
  • 4
  • 53
  • 63
0

You can use System.currentTimeMillis() to return the current time in milliseconds after that, you can do some math to figure out hours, minutes, and seconds.

    long totalMolilliseconds = System.currentTimeMillis();
    long totalSeconds = totalMolilliseconds / 1000;
    long currentSeconds = totalSeconds % 60;
    long totalMinutes = totalSeconds / 60;
    long currentMinutes = totalMinutes % 60;
    long totalHours = totalMinutes / 60;
    long currentHours = totalHours % 24;
Hamid
  • 114
  • 1
  • 3
  • While I believe it works, it is not the recommended way. Better to use the library classes for self-explanatory and readable code that also convinces the reader that it is correct. – Ole V.V. Jul 04 '18 at 07:15