如何分别检索时间字段?

时间:2018-07-04 06:25:27

标签: java datetime

我使用此代码将当前时间转换为整数格式

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

现在我要从整数int x中分别获取实际的日期值(年,月,日期,小时,分钟)。

我该怎么做?

谢谢(请引导我)

2 个答案:

答案 0 :(得分:3)

使用Java 8,您可以在LocalDate

中轻松进行管理
    LocalDate today = LocalDate.now();
    int thisYear = today.getYear();
    int thisMonth = today.getMonthValue();
    int thisDay = today.getDayOfMonth();
    out.println(thisYear + "-" + thisMonth + "-" + thisDay);

但是当您尝试实现更高的目标(小时,分钟,秒)时,您可以转向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);

然后输出将是:+

2018-7-4
2018-7-4 14:33:12

答案 1 :(得分:0)

您可以使用System.currentTimeMillis()以毫秒为单位返回当前时间,然后可以做一些数学运算来计算小时,分钟和秒。

    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;