日期对象到日历 [Java]

发布于 2024-08-30 12:48:50 字数 241 浏览 2 评论 0原文

我有一堂课电影 其中我有一个开始日期、持续时间和停止日期。 开始和停止日期是日期对象(private Date startDate ...) (这是一项任务,所以我无法更改) 现在我想通过将持续时间(以分钟为单位)添加到开始日期来自动计算停止日期。

据我所知,使用 Date 的时间操作函数已被弃用,因此是不好的做法,但另一方面,我认为没有办法将 Date 对象转换为日历对象来操作时间并将其重新转换为 Date 对象。 有办法吗?如果有什么是最佳实践

I have a class Movie
in it i have a start Date, a duration and a stop Date.
Start and stop Date are Date Objects (private Date startDate ...)
(It's an assignment so i cant change that)
now I want to automatically calculate the stopDate by adding the duration (in min) to the startDate.

By my knowledge working with the time manipulating functions of Date is deprecated hence bad practice but on the other side i see no way to convert the Date object to a calendar object in order to manipulate the time and reconvert it to a Date object.
Is there a way? And if there is what would be best practice

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

谁与争疯 2024-09-06 12:48:50

您可以做的是创建 GregorianCalendar 的实例,然后将 Date 设置为开始时间:

Date date;
Calendar myCal = new GregorianCalendar();
myCal.setTime(date);

但是,另一种方法是不使用 Date > 完全没有。您可以使用这样的方法:

private Calendar startTime;
private long duration;
private long startNanos;   //Nano-second precision, could be less precise
...
this.startTime = Calendar.getInstance();
this.duration = 0;
this.startNanos = System.nanoTime();

public void setEndTime() {
        this.duration = System.nanoTime() - this.startNanos;
}

public Calendar getStartTime() {
        return this.startTime;
}

public long getDuration() {
        return this.duration;
}

通过这种方式,您可以访问开始时间并获取从开始到停止的持续时间。当然,精度取决于你。

What you could do is creating an instance of a GregorianCalendar and then set the Date as a start time:

Date date;
Calendar myCal = new GregorianCalendar();
myCal.setTime(date);

However, another approach is to not use Date at all. You could use an approach like this:

private Calendar startTime;
private long duration;
private long startNanos;   //Nano-second precision, could be less precise
...
this.startTime = Calendar.getInstance();
this.duration = 0;
this.startNanos = System.nanoTime();

public void setEndTime() {
        this.duration = System.nanoTime() - this.startNanos;
}

public Calendar getStartTime() {
        return this.startTime;
}

public long getDuration() {
        return this.duration;
}

In this way you can access both the start time and get the duration from start to stop. The precision is up to you of course.

等往事风中吹 2024-09-06 12:48:50
Calendar tCalendar = Calendar.getInstance();
tCalendar.setTime(date);

date 是一个 java.util.Date 对象。您也可以使用 Calendar.getInstance() 来获取 Calendar 实例(效率更高)。

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

date is a java.util.Date object. You may use Calendar.getInstance() as well to obtain the Calendar instance(much more efficient).

木槿暧夏七纪年 2024-09-06 12:48:50

日历.setTime()

查看 API 方法的签名和描述,而不仅仅是它们的名称,通常很有用:) - 即使在 Java 标准 API 中,名称有时也可能会产生误导。

Calendar.setTime()

It's often useful to look at the signature and description of API methods, not just their name :) - Even in the Java standard API, names can sometimes be misleading.

会傲 2024-09-06 12:48:50

您不需要为此转换为 Calendar,只需使用 getTime()/setTime() 即可。

getTime ()
返回此 Date 对象表示的自 1970 年 1 月 1 日 00:00:00 GMT 以来的毫秒数。

setTime (long time) :设置此 Date 对象来表示 1970 年 1 月 1 日 00:00:00 GMT 之后的时间点(毫秒)。 )

一秒有 1000 毫秒,一分钟有 60 秒。只要算一下就可以了。

    Date now = new Date();
    Date oneMinuteInFuture = new Date(now.getTime() + 1000L * 60);
    System.out.println(now);
    System.out.println(oneMinuteInFuture);

1000 中的 L 后缀表示它是一个 long 文字;这些计算通常很容易溢出int

You don't need to convert to Calendar for this, you can just use getTime()/setTime() instead.

getTime():
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

setTime(long time) : Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT. )

There are 1000 milliseconds in a second, and 60 seconds in a minute. Just do the math.

    Date now = new Date();
    Date oneMinuteInFuture = new Date(now.getTime() + 1000L * 60);
    System.out.println(now);
    System.out.println(oneMinuteInFuture);

The L suffix in 1000 signifies that it's a long literal; these calculations usually overflows int easily.

擦肩而过的背影 2024-09-06 12:48:50

tl;dr

Instant stop = 
    myUtilDateStart.toInstant()
                   .plus( Duration.ofMinutes( x ) ) 
;

java.time

其他答案是正确的,尤其是 Borgwardt 的答案。但这些答案使用过时的遗留类。

与 Java 捆绑在一起的原始日期时间类已被 java.time 类取代。在 java.time 类型中执行业务逻辑。仅在需要使用尚未更新以处理 java.time 类型的旧代码时转换为旧类型。

如果您的日历 实际上是一个 GregorianCalendar 您可以转换为 ZonedDateTime。查找添加到旧类中的新方法,以方便与 java.time 类型之间的转换。

if( myUtilCalendar instanceof GregorianCalendar ) {
    GregorianCalendar gregCal = (GregorianCalendar) myUtilCalendar; // Downcasting from the interface to the concrete class.
    ZonedDateTime zdt = gregCal.toZonedDateTime();  // Create `ZonedDateTime` with same time zone info found in the `GregorianCalendar`
end if 

如果您的日历不是公历,请调用toInstant 获取 Instant 对象。 即时 类代表 UTC 中时间轴上的时刻,分辨率为 纳秒

Instant instant = myCal.toInstant();

同样,如果从 java.util.Date 对象开始,请转换为 Instant即时 类代表 UTC 中时间轴上的时刻,分辨率为 纳秒(最多九 (9) 位小数)。

Instant instant = myUtilDate.toInstant();

应用时区来获取 ZonedDateTime< /代码>

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

要获取 java.util.Date 对象,请通过 Instant

java.util.Date utilDate = java.util.Date.from( zdt.toInstant() );

有关旧日期时间类型和 java.time 之间转换的更多讨论以及漂亮的图表,请参阅我的回答另一个问题。

Duration

将时间跨度表示为 Duration 对象。您输入的持续时间是问题中提到的分钟数。

Duration d = Duration.ofMinutes( yourMinutesGoHere );

您可以将其添加到开始位置以确定停止位置。

Instant stop = startInstant.plus( d ); 

关于 java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date, 日历, & ; SimpleDateFormat

Joda-Time 项目,现已在 维护模式,建议迁移到 java.time。

要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范为 JSR 310

从哪里获取 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如 间隔YearWeek<代码>YearQuarter,以及更多

tl;dr

Instant stop = 
    myUtilDateStart.toInstant()
                   .plus( Duration.ofMinutes( x ) ) 
;

java.time

Other Answers are correct, especially the Answer by Borgwardt. But those Answers use outmoded legacy classes.

The original date-time classes bundled with Java have been supplanted with java.time classes. Perform your business logic in java.time types. Convert to the old types only where needed to work with old code not yet updated to handle java.time types.

If your Calendar is actually a GregorianCalendar you can convert to a ZonedDateTime. Find new methods added to the old classes to facilitate conversion to/from java.time types.

if( myUtilCalendar instanceof GregorianCalendar ) {
    GregorianCalendar gregCal = (GregorianCalendar) myUtilCalendar; // Downcasting from the interface to the concrete class.
    ZonedDateTime zdt = gregCal.toZonedDateTime();  // Create `ZonedDateTime` with same time zone info found in the `GregorianCalendar`
end if 

If your Calendar is not a Gregorian, call toInstant to get an Instant object. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.

Instant instant = myCal.toInstant();

Similarly, if starting with a java.util.Date object, convert to an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = myUtilDate.toInstant();

Apply a time zone to get a ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

To get a java.util.Date object, go through the Instant.

java.util.Date utilDate = java.util.Date.from( zdt.toInstant() );

For more discussion of converting between the legacy date-time types and java.time, and a nifty diagram, see my Answer to another Question.

Duration

Represent the span of time as a Duration object. Your input for the duration is a number of minutes as mentioned in the Question.

Duration d = Duration.ofMinutes( yourMinutesGoHere );

You can add that to the start to determine the stop.

Instant stop = startInstant.plus( d ); 

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

漫漫岁月 2024-09-06 12:48:50

在 Kotlin 中将日期转换为日历的扩展。

fun Date?.toCalendar(): Calendar? {
    return this?.let { date ->
        val calendar = Calendar.getInstance()
        calendar.time = date
        calendar
    }
}

Extension for converting date to calendar in Kotlin.

fun Date?.toCalendar(): Calendar? {
    return this?.let { date ->
        val calendar = Calendar.getInstance()
        calendar.time = date
        calendar
    }
}
壹場煙雨 2024-09-06 12:48:50

类似的东西

movie.setStopDate(movie.getStartDate() + movie.getDurationInMinutes()* 60000);

something like

movie.setStopDate(movie.getStartDate() + movie.getDurationInMinutes()* 60000);
猫弦 2024-09-06 12:48:50

以下是有关如何将日期转换为不同类型的完整示例:

Date date = Calendar.getInstance().getTime();

    // Display a date in day, month, year format
    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    String today = formatter.format(date);
    System.out.println("Today : " + today);

    // Display date with day name in a short format
    formatter = new SimpleDateFormat("EEE, dd/MM/yyyy");
    today = formatter.format(date);
    System.out.println("Today : " + today);

    // Display date with a short day and month name
    formatter = new SimpleDateFormat("EEE, dd MMM yyyy");
    today = formatter.format(date);
    System.out.println("Today : " + today);

    // Formatting date with full day and month name and show time up to
    // milliseconds with AM/PM
    formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
    today = formatter.format(date);
    System.out.println("Today : " + today);

Here is a full example on how to transform your date in different types:

Date date = Calendar.getInstance().getTime();

    // Display a date in day, month, year format
    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    String today = formatter.format(date);
    System.out.println("Today : " + today);

    // Display date with day name in a short format
    formatter = new SimpleDateFormat("EEE, dd/MM/yyyy");
    today = formatter.format(date);
    System.out.println("Today : " + today);

    // Display date with a short day and month name
    formatter = new SimpleDateFormat("EEE, dd MMM yyyy");
    today = formatter.format(date);
    System.out.println("Today : " + today);

    // Formatting date with full day and month name and show time up to
    // milliseconds with AM/PM
    formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
    today = formatter.format(date);
    System.out.println("Today : " + today);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文