获取第二天的 java.sql.Date
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7432143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get next day java.sql.Date
提问by tiran
I have a Date object (java.sql.Date
). I need to get 12 at night of that day. So I can create a time period from current time to end of the day.
我有一个 Date 对象 ( java.sql.Date
)。我需要在那天晚上得到 12。所以我可以创建一个从当前时间到一天结束的时间段。
How can I calculate that time with java.sql.Date
. Please send me an example.
我怎样才能用java.sql.Date
. 请给我一个例子。
回答by Jarek Przygódzki
Using java.util.Calendar
java.sql.Date sqlDate = ...;
Calendar cal = Calendar.getInstance();
cal.setTime(sqlDate);
cal.add(Calendar.DAY_OF_YEAR,1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
java.sql.Date sqlTommorow = new java.sql.Date(cal.getTimeInMillis());
回答by Jon Skeet
Ideally, use Joda Timewhich is a muchbetter date and time API than the one in Java.
理想的情况下,使用约达时间是一个多更好的日期和时间API一个比Java的。
java.sql.Date sqlDate = ...;
LocalDate date = new LocalDate(sqlDate.getTime(), DateTimeZone.UTC);
LocalDate tomorrow = date.plusDays(1);
DateTime startOfDay = tomorrow.toDateTimeAtStartOfDay(DateTimeZone.UTC);
java.sql.Date sqlTomorrow = new java.sql.Date(startOfDay.getMillis());
Note that this assumes UTC everywhere... whereas I suspect you want midnight local timein which case you'll need to specify the time zone. Also note that midnight doesn't always occur on every day in all time zones due to daylight saving time - the above code will give you the start of the day instead.
请注意,这假定 UTC 无处不在......而我怀疑您想要当地时间午夜,在这种情况下,您需要指定时区。另请注意,由于夏令时,并非所有时区的每一天都发生午夜 - 上面的代码将为您提供一天的开始。
回答by user2250095
Use the following code:
使用以下代码:
java.sql.Date now = new java.sql.Date( new java.util.Date().getTime() );
java.sql.Date tomorrow= new java.sql.Date( now.getTime() + 24*60*60*1000);
回答by systemkern
this is probably not the nicest way, but IMHO it's relatively easy to understand. It creates a new midnight java.sql.Date object for the input date "now"
这可能不是最好的方式,但恕我直言,它相对容易理解。它为输入日期“现在”创建一个新的午夜 java.sql.Date 对象
String DATE_FORMAT = "dd.MM.yyyy";
//create a date sql.Date object
java.sql.Date now = new java.sql.Date( new java.util.Date().getTime() );
//create a date formatter
SimpleDateFormat sf = new SimpleDateFormat(DATE_FORMAT);
//get the midnight date by converting the object to a String and back to a Date object
java.util.Date midnightUtil = sf.parse( sf.format( now ) );
//create a new java.sql.Date object and add one days worth of milliseconds;
java.sql.Date midnight = new java.sql.Date( midnightUtil.getTime() + 86400000 );