hudi
hudi

Reputation: 16525

How to get current date with custom hour?

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

Answers (4)

Jon Skeet
Jon Skeet

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

James
James

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

Mohamed Habib
Mohamed Habib

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

Michaël
Michaël

Reputation: 3671

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 1);
cal.set(Calendar.MINUTE, 0);
cal.getTime()

Upvotes: 0

Related Questions