将 1 周添加到日期,首选哪种方式?

Add 1 Week to a Date, which way is preferred?(将 1 周添加到日期,首选哪种方式?)
本文介绍了将 1 周添加到日期,首选哪种方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在审查一些工作中的代码,并发现代码处理将当前时间增加 1 周的方式不一致,我想知道是否有任何理由真正应该优先于另一个:

I am reviewing some code at work and came across an inconsistency in how the code handles adding 1 week to the current time and was wondering if there was any reason why one should really be preferred over the other:

第一个是实用方法:

public static Date addDaysToDate(final Date date, int noOfDays) {
    Date newDate = new Date(date.getTime());

    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(newDate);
    calendar.add(Calendar.DATE, noOfDays);
    newDate.setTime(calendar.getTime().getTime());

    return newDate;
}

第二个使用简单的毫秒算术:

And the second used simple millisecond arithmetic:

long theFuture = System.currentTimeMillis() + (86400 * 7 * 1000);
Date nextWeek = new Date(theFuture);

第二种方法显然使用幻数"来定义一周,但这可以移动到一个常数 MILLISECONDS_IN_ONE_WEEK = 86400 * 7 * 1000 那么除此之外,还有什么原因这些方法中的哪一种应该优于其他方法?

The second method obviously uses 'magic numbers' to define a week, but this could be moved to a constant MILLISECONDS_IN_ONE_WEEK = 86400 * 7 * 1000 So other than that, is there any reasons why one of these methods should be preferred over the other?

基本上我想更改代码以使其始终保持一致,但我不完全确定要删除哪一个.因此,任何一种或另一种方式的论点都是有用的.

Basically I want to change the code to be consistent throughout, but I'm not entirely sure which one to remove. So any arguments one way or the other would be useful.

推荐答案

这两种方法在夏令时边界上的行为会有所不同.第一种方法将继续返回一天中的同一时间,无论夏令时状态如何.第二种方法将返回随着夏令时开始和停止而在每个方向变化一小时的时间.

The two methods will behave differently on daylight savings boundaries. The first method will continue returning the same time of the day, regardless of daylight savings status. The second method will return times which vary an hour in each direction as daylight savings time starts and stops.

这篇关于将 1 周添加到日期,首选哪种方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Month is not printed from a date - Java DateFormat(月份不是从日期打印的 - Java DateFormat)
java get week of year for given a date(java获取给定日期的一年中的一周)
Get the number of days, weeks, and months, since Epoch in Java(获取自 Java 中的 Epoch 以来的天数、周数和月数)
Is there a good way to get the date of the coming Wednesday?(有什么好方法可以得到即将到来的星期三的日期吗?)
Calendar view for Android GingerBread and before (APIlt;11)(Android GingerBread 及之前的日历视图 (API11))
How to save and retrieve Date in SharedPreferences(如何在 SharedPreferences 中保存和检索日期)