我需要第一次和最后一次获得昨天。例如,今天11月18日我需要输出
2013-11-17 00:00:00
和
2013-11-17 23:59:59
如何获得这个?
我可以手动获取(比如获取昨天的日期(17)并自己输入其余的值)但我需要以编程方式完整表格
答案 0 :(得分:7)
在Java 8中,您可以通过java.time
API:
LocalDateTime yesterday = LocalDateTime.now().minus(1, ChronoUnit.DAYS);
LocalDateTime time1 = yesterday.with(LocalTime.of(0, 0, 0));
LocalDateTime time2 = yesterday.with(LocalTime.of(23, 59, 59));
(在Java 7中也不难,但聪明得多)
答案 1 :(得分:3)
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(sdf.format(cal.getTime()));
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);
System.out.println(sdf.format(cal.getTime()));
答案 2 :(得分:3)
使用Groovy,您可以获得:
new Date().previous().clearTime().toCalendar().with { cal ->
println format( "yyyy-MM-dd HH:mm:ss" )
add( Calendar.DAY_OF_YEAR, 1 )
add( Calendar.SECOND, -1 )
println format("yyyy-MM-dd HH:mm:ss")
}
或者:
def dates = new Date().clearTime().with { d ->
use( groovy.time.TimeCategory ) {
[ d - 1.day, d - 1.second ]
}
}
dates.each { println it.format( 'yyyy-MM-dd HH:mm:ss' ) }
答案 3 :(得分:0)
Elliott给了我们一个很好的Java解决方案。
Groovyer方式将是这样的:
import java.text.SimpleDateFormat
def sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
def cal = new Date().previous().toCalendar() // Obtain previous date
cal.set(Calendar.HOUR, 0) // initialise it
cal.set(Calendar.MINUTE, 0)
cal.set(Calendar.SECOND, 0)
println sdf.format(cal.time)
cal++ // Go one day up
cal.add(Calendar.SECOND, -1) // Step back by second
println sdf.format(cal.time)
答案 4 :(得分:0)
另一种方法:
Date getTodayStart( Date inDate){
Calendar cal = Calendar.getInstance()
cal.set(inDate[Calendar.YEAR], inDate[Calendar.MONTH], inDate[Calendar.DATE], 0, 0, 0)
Date todayStart = cal.getTime()
return todayStart
}
Date getTodayEnd(Date inDate){
Calendar cal = Calendar.getInstance()
cal.set(inDate[Calendar.YEAR], inDate[Calendar.MONTH], inDate[Calendar.DATE], 0, 0, -1)
Date todayEnd = cal.getTime() + 1
return todayEnd
}
并调用这些方法:
Date startDate = getTodayStart(date)
Date endDate = getTodayEnd(date)