有了
JodaTime
,不使用“加号”或“减号”功能,使用最少的代码行,如何在不修改时间的情况下设置新的日期?
我的第一次尝试是使用
DateTime
和 int
等将 getHoursOfDay()
的“时间”部分存储在单独的 getMinutesOfHour()
中 - 然后创建一个具有所需日期的新 DateTime
并设置小时、分钟,然后再次返回秒数。但这种方法非常笨重,我想知道是否有一种不太冗长的方法可以做到这一点 - 最好只用一行代码。
例如:
22/05/2013 13:40:02
>>>> 30/08/2014 13:40:02
JodaTime 是必须的吗?执行此操作的基本方法是 1.从时间戳中提取时间。 2.将此添加到刚刚的日期
long timestamp = System.currentTimeMillis(); //OK we have some timestamp
long justTime = timestamp % 1000 * 60 * 60 * 24;// just tiem contains just time part
long newTimestamp = getDateFromSomeSource();//now we have date from some source
justNewDate = newTimestamp - (newTimestamp % 1000 * 60 * 60 * 24);//extract just date
result = justNewDate + justTime;
类似这样的事情。
你可以这样做
DateTime myDate = ...
myDate.withDate(desiredYear, desiredMonth, desiredDayOfMonth);
JavaDoc在这里:DateTime.withDate(intyear,intmonth,intdayOfMonth)
像这样使用withFields:
new DateTime().withFields(new LocalDate(2000,1,1))
这会将
DateTime
的所有日期时间字段设置为 LocalDate
中包含的日期时间字段 - 在本例中为年、月和日。这适用于任何 ReadablePartial
实现,例如 YearMonth
。