【问题标题】:how to subtract the day in date format in java如何在java中以日期格式减去日期
【发布时间】:2016-10-15 15:16:42
【问题描述】:

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

我/p:

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

• 然后它将进入循环。

我必须在里面做一些计算。但是如何在格式中单独减去日期值,它应该返回 1 否则从条件中出来

谁能帮帮我

谢谢

【问题讨论】:

  • 您到底想计算什么?两个日期之间的时间差?
  • 没有。只想减去日期。例如 ('2016-02-14 20:10:10') - day ('2016-02-15 16:00:00') 它会给出结果 (15 - 14) = 1
  • 将这些转换为毫秒并考虑 1 天是 24*3600.... 或使用日历对象
  • 你的意思是得到一整天的时差?
  • 如果是java8那么你可以使用DAYS.between(localDate1, localDate2)

标签: java date hadoop hive


【解决方案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();
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-06-09
  • 2011-11-17
  • 2012-10-13
  • 1970-01-01
  • 1970-01-01
  • 2011-04-01
  • 2023-04-06
  • 2016-12-08
相关资源
最近更新 更多