如何在Java中将日期和SQL时间组合成单个日期时间?

huangapple go评论80阅读模式
英文:

how can you combine date and sql time into a single date time in java?

问题

使用Java Calendar,您可以如何将开始日期、天数和开始时间组合在一起?

例如:

如果开始日期是9/8/2020,天数是2,开始时间是8:00 AM,那么我们如何获得一个Java日期,即9/9/2020 8:00 AM?以下是我的尝试:

import java.util.Calendar;
import java.util.Date;

public Date startDateTime(Date startDate, int day, java.sql.Time startTime) {    

    Calendar date = Calendar.getInstance();
    date.setTime(startDate);

    // 添加天数。由于第1天是第一天,我们需要添加day - 1
    date.add(Calendar.DATE, day - 1);
    
    // 设置时间为startTime的时间
    Calendar time = Calendar.getInstance();
    time.setTimeInMillis(startTime.getTime());
    
    date.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
    date.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
    date.set(Calendar.SECOND, time.get(Calendar.SECOND));

    return date.getTime();
}

谢谢您的帮助。

英文:

Using java Calendar how can you combine the start date, day and starttime?

For example:

If the start date is 9/8/2020. The day is 2 and the start time is 8:00 AM then how can we obtain a java date that is 9/9/2020 8:00 AM. Here is my unsuccessful attempt.

def startDateTime(Date startDate, int day, java.sql.Time startTime){    

		def date
		date = Calendar.getInstance()
		date.setTime(startDate)

        //adding day. since day 1 is the first day we need to add day - 1
		date.add(Calendar.DATE, day - 1)   
        // setting the time from startTime
		date.setTimeInMillis(startTime.getTime())
    
		return date.getTime()

	}

Thanks for the help.

答案1

得分: 1

你正在调用date.setTime(startDate)date.setTimeInMillis(startTime.getTime())。第二个方法会覆盖第一个方法设置的时间。你应该创建两个单独的Calendar实例。

以下是如何实现这一点:

  1. startDaystartTime创建单独的Calendar实例。
  2. 根据需要从在步骤1中创建的单独的Calendar对象构造一个新的Calendar对象,并添加day

以下是完整的代码:

import java.sql.Time;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;

public class ProofOfConcept {

    public static void main(String[] args) {
        int day = 2;

        Time startTime = new Time(1, 1, 1);
        Calendar timeCalendar = Calendar.getInstance();
        timeCalendar.setTime(startTime);

        Date startDate = new Date();
        Calendar startDateCalendar = Calendar.getInstance();
        startDateCalendar.setTime(startDate);

        Calendar result = Calendar.getInstance();
        result.set(startDateCalendar.get(Calendar.YEAR), startDateCalendar.get(Calendar.MONTH), startDateCalendar.get(Calendar.DAY_OF_MONTH) + 2,
                timeCalendar.get(Calendar.HOUR), timeCalendar.get(Calendar.MINUTE), timeCalendar.get(Calendar.SECOND));

        Date date = result.getTime();
        System.out.println("date : " + date);
    }
}

输出:

date : Tue Sep 08 01:01:01 IST 2020

注意:我建议在java.util.*之上使用java.time.*包。为什么?请查看这里。但这仅适用于Java 8及以上。(尽管在8以下版本中可以使用joda time)


编辑:将Ole V.V.的评论移到答案中。

对于Java 7,我建议通过后移ThreeTen Backport来使用现代Java日期和时间API,即java.time

static LocalDateTime startDateTime(Date startDate, int day, java.sql.Time startTime) {
    LocalTime startLocalTime = DateTimeUtils.toLocalTime(startTime);
    return DateTimeUtils.toInstant(startDate)
            .atZone(ZoneId.systemDefault())
            .toLocalDate()
            .plusDays(day - 1)
            .atTime(startLocalTime);
}
英文:

You are calling date.setTime(startDate) and date.setTimeInMillis(startTime.getTime()). 2nd method is overriding the time set in 1st method. You should create 2 separate instances of Calendar.

Here is how you can achieve this

  1. Create separate Calendar instances for startDay and startTime
  2. Construct a new Calendar object from separate Calendar objects created in #1 & add day as per requirement

Here is the complete code:

import java.sql.Time;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;

public class ProofOfConcept {

    public static void main(String[] args) {
        int day = 2;

        Time startTime = new Time(1, 1, 1);
        Calendar timeCalendar = Calendar.getInstance();
        timeCalendar.setTime(startTime);

        Date startDate = new Date();
        Calendar startDateCalendar = Calendar.getInstance();
        startDateCalendar.setTime(startDate);

        /* Only java 8 and above
        LocalDateTime localDateTime = LocalDateTime.of(startDateCalendar.get(Calendar.YEAR), startDateCalendar.get(Calendar.MONTH) + 1, startDateCalendar.get(Calendar.DAY_OF_MONTH),
                timeCalendar.get(Calendar.HOUR), timeCalendar.get(Calendar.MINUTE), timeCalendar.get(Calendar.SECOND));
        localDateTime = localDateTime.plusDays(day);
        System.out.println("localDateTime : " + localDateTime);
        Date dateFromLocalDateTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        System.out.println("dateFromLocalDateTime : " + dateFromLocalDateTime);*/

        Calendar result = Calendar.getInstance();
        result.set(startDateCalendar.get(Calendar.YEAR), startDateCalendar.get(Calendar.MONTH), startDateCalendar.get(Calendar.DAY_OF_MONTH) + 2,
                timeCalendar.get(Calendar.HOUR), timeCalendar.get(Calendar.MINUTE), timeCalendar.get(Calendar.SECOND));

        Date date = result.getTime();
        System.out.println("date : " + date);
    }

}

Output:
> date : Tue Sep 08 01:01:01 IST 2020

Note : I suggest using java.time.* packages over java.util.*. Why? Check this. But this is only available in java 8. (Though, you can use joda time in versions below 8).


Edit : Moving Ole V.V. 's comment to answer.

For Java 7, I suggest using java.time, the modern Java date and time API, through the backport, ThreeTen Backport.

static LocalDateTime startDateTime(Date startDate, int day, java.sql.Time startTime) {
	LocalTime startLocalTime = DateTimeUtils.toLocalTime(startTime);
	return DateTimeUtils.toInstant(startDate)
			.atZone(ZoneId.systemDefault())
			.toLocalDate()
			.plusDays(day - 1)
			.atTime(startLocalTime);
}

huangapple
  • 本文由 发表于 2020年9月6日 13:08:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63760901.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定