将1周添加到日期,首选方式是什么? [英] Add 1 Week to a Date, which way is preferred?

查看:144
本文介绍了将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:

第一个是一个实用方法:

The first was a utility method:

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周添加到日期,首选方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆