java - 如何在Java中以日期格式减去日期

标签 java date hadoop hive

我一直在努力减去日期格式值。

i / p:

如果选择日期('2016-02-14 20:10:10')-天('2016-02-15 16:00:00')---返回1

•然后它将进入循环。

我必须在里面做一些计算。但是如何单独减去格式中的日期值,它应该返回1,否则就会出现这种情况

谁能帮帮我吗

谢谢

最佳答案

这是三种选择:

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public class Test{

    public static void main(String[] arguments) {

        String sDateString = "2016-02-14 20:10:10";
        String eDateString = "2016-02-15 20:10:10";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date startDate = null, endDate = null;
        try {
            startDate = df.parse(sDateString);
            endDate = df.parse(eDateString);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //difference in milliseconds
        long diff = endDate.getTime() - startDate.getTime();

        //difference in days
        System.out.println(diff/(3600*24*1000));

        ///////////////////////////////////////////////////////////////
        //Alternatively , use java 8
        LocalDate startLocalDate = LocalDateFromDate(startDate);
        LocalDate endLocalDate = LocalDateFromDate(endDate);
        //difference in days
        System.out.println(ChronoUnit.DAYS.between(startLocalDate, endLocalDate));

        ///////////////////////////////////////////////////////////////
        //Alternatively, if the String representation of date is fixed
        //you can extract the string representing the day of the month
        //not recommended)

        //find index 0f last "-"
        int sIndex = sDateString.lastIndexOf("-");
        //get the day in month substring, remove spaces 
        String s = sDateString.substring(sIndex+1,sIndex+3).trim();

        int eIndex = sDateString.lastIndexOf("-");
        String e = eDateString.substring(sIndex+1,sIndex+3).trim();

        //difference in days
        System.out.println(Integer.parseInt(e) - Integer.parseInt(s));
    }

    public static LocalDate LocalDateFromDate(Date date) {

        Instant instant = Instant.ofEpochMilli(date.getTime());
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
                .toLocalDate();
    }
}

关于java - 如何在Java中以日期格式减去日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40055524/

相关文章:

Java动态创建实例变量的对象数组

java - 信息丰富的 Java 游戏开发教程?

javascript - 解析像 2012-11-07T00 :00:00 这样的日期

hadoop - 使用 Spark 通过 Cloudera Hadoop 从 Cassandra 读取数据

java - 打开项目时在 Eclipse 2018-12 中找不到自动模块

Excel SUMIF 使用由单元格值定义的文本和日期范围

java - JacksonMapper 使用 UTC 时区的日期反序列化在给定格式下失败

hadoop - 在 pyspark 数据帧计数函数中得到 `java.nio.BufferOverflowException`

java - 如果PowerMock测试之前运行,则本地集成测试将失败

java静态同步方法