简体   繁体   中英

How to get date from milliseconds

Hi All I have a requirement where i need to check date with system date value but the date value i have in DB is in milliseconds so below are my code but the problem is the system date which i get display month value incorrect its display month value one month less .

    Date now = new Date();
    Long nowLong = now.getTime() / 1000;
    Integer unixTime = nowLong.intValue();

    Calendar cal;
    cal = Calendar.getInstance();
    cal.setTimeInMillis(unixTime * 1000L);

    Integer day = cal.get(Calendar.DAY_OF_MONTH);
    Integer month = cal.get(Calendar.MONTH);
    Integer hour = cal.get(Calendar.HOUR);
    Integer minute = cal.get(Calendar.MINUTE);
    String amPm = (cal.get(Calendar.AM_PM) == Calendar.PM) ? "PM" : "AM";
    Integer year = cal.get(Calendar.YEAR);

    System.out.println("day :" + day);
    System.out.println("month :" + month);
    System.out.println("hour " + hour);
    System.out.println("minute " + minute);
    System.out.println("amPm " + amPm);
    System.out.println("year " + year);

For this the output is day :3 month :4 hour 3 minute 13 amPm PM year 2016 but output is not correct . Can any one help me .

In Java the value returned by cal.get(Calendar.MONTH) is zero bazed . Thenf JANUARY = 0 , FEBRUARY = 0 , ... (documentation here )

Try this :

Integer month = cal.get(Calendar.MONTH) + 1;

Or this :

System.out.println("month :" + (month.intValue() + 1));

Note the creation of your calendar can be simpler:

Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());

try using LocalDate . there has been lot of changes to Date Time api in java 8 .you can do it better with LocalDate.

LocalDate today = LocalDate.now(); //current date
today.getMonth() //getMonth as a string
today.getMonth()//getMonthValue in an int
today.getDayOfWeek() // get the date in a string format
today.getDayOfMonth() //get the date as an int.
today.getYear()//get the year

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM