Reputation: 16525
I need to get actual date with custom hour so I create this code:
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
Calendar output = Calendar.getInstance();
output.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 1, 0);
output.getTime();
I hope it works but it seems a litle bit complicated.
Is there some other way how to get date with custom hour?
Upvotes: 1
Views: 573
Reputation: 1499860
Is there some other way how to get date with custom hour ?
Personally I'd use Joda Time instead:
// Ideally use an injectable clock...
LocalDate today = new LocalDate();
// If this is effectively constant, extract it to a final static field
LocalTime time = new LocalTime(1, 0);
// Or use toDateTime(...) depending on what you're trying to accomplish
LocalDateTime todayAtTime = today.toLocalDateTime(time);
Joda Time has a much more pleasant API than java.util.{Date, Calendar}
Upvotes: 3
Reputation: 1571
Other than use Joda time I'd do it slightly cleaner:
int hour = 1;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, hour);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar.getInstance()
returns the current date and time anyway so setTime(new Date())
is unnecessary.
Upvotes: 0
Reputation: 903
what about this :
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, your_custom_hour);
your_custom_hour : 0-23
Upvotes: 0
Reputation: 3671
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 1);
cal.set(Calendar.MINUTE, 0);
cal.getTime()
Upvotes: 0