Java Date Cut Off Time Information

Java Date cut off time information

The recommended way to do date/time manipulation is to use a Calendar object:

Calendar cal = Calendar.getInstance(); // locale-specific
cal.setTime(dateObject);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long time = cal.getTimeInMillis();

Removing time from a Date object?

The quick answer is :

No, you are not allowed to do that. Because that is what Date use for.

From javadoc of Date :

The class Date represents a specific instant in time, with millisecond precision.

However, since this class is simply a data object. It dose not care about how we describe it.
When we see a date 2012/01/01 12:05:10.321, we can say it is 2012/01/01, this is what you need.
There are many ways to do this.

Example 1 : by manipulating string

Input string : 2012/01/20 12:05:10.321

Desired output string : 2012/01/20

Since the yyyy/MM/dd are exactly what we need, we can simply manipulate the string to get the result.

String input = "2012/01/20 12:05:10.321";
String output = input.substring(0, 10); // Output : 2012/01/20

Example 2 : by SimpleDateFormat

Input string : 2012/01/20 12:05:10.321

Desired output string : 01/20/2012

In this case we want a different format.

String input = "2012/01/20 12:05:10.321";
DateFormat inputFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = inputFormatter.parse(input);

DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
String output = outputFormatter.format(date); // Output : 01/20/2012

For usage of SimpleDateFormat, check SimpleDateFormat JavaDoc.

Java: How to deal with cutoff timing for a system?

I have written a class which is able to represent cutoff timings for systems (uptimes or downtimes).

The difficulty of the use case within the question is that the end time lies before the start time. That implies that the downtime starts at some day of the week, and ends the next day at a certain time.

So Monday until Friday, from 18:00 until 07:00, implies that the system is also down on Saturday, midnight until 7:00. If we want to handle this correctly, we need to take that into account.

Below the source code of the class. The constructor accepts a Set with the days of the week at which the cutoff times start, and the start and end times.

public class Uptime {

private final Set<DayOfWeek> daysOfUptimeStart;

private final LocalTime startTime;

private final LocalTime endTime;

public Uptime(Set<DayOfWeek> daysOfUptimeStart, LocalTime startTime, LocalTime endTime) {
this.daysOfUptimeStart = Collections.unmodifiableSet(daysOfUptimeStart);
this.startTime = startTime;
this.endTime = endTime;
}

public boolean isUp(LocalDateTime dateTime) {
LocalTime time = dateTime.toLocalTime();
if (!this.startTime.isAfter(this.endTime)) {
return this.daysOfUptimeStart.contains(dateTime.getDayOfWeek()) && !time.isBefore(this.startTime) && !time.isAfter(this.endTime);
}
else {
if (time.isBefore(this.startTime) && time.isAfter(this.endTime)) {
return false;
}
else {
return this.daysOfUptimeStart.contains(dateTime.getDayOfWeek().minus(!time.isBefore(this.startTime) ? 0 : 1));
}
}
}
}

Test

In order to test this, I have generated some dates: all dates from 14 to 20 September 2020 (Monday to Sunday), combined with 4 AM, 8 AM, 1 PM, 5 PM, 7 PM and 11 PM.

The code prints the datetimes, along with whether the system is up or not. We expect that:

  • on Monday, the system is down at 7 PM and 11 PM;
  • on Tuesday until Friday, the system is down at 4 AM, 7 PM and 11 PM;
  • on Saturday, the system is down at 4 AM.
// Static importing java.time.DayOfWeek.* here
Uptime uptime = new Uptime(Set.of(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY), LocalTime.of(18, 0), LocalTime.of(7, 0));

YearMonth ym = YearMonth.of(2020, Month.SEPTEMBER);
List<LocalDateTime> datetimes = IntStream.rangeClosed(14, 20) // September 2020, MONDAY till SUNDAY
.mapToObj(ym::atDay)
.flatMap(date -> IntStream.of(4, 8, 13, 17, 19, 23)
.mapToObj(hour -> LocalTime.of(hour, 0))
.map(date::atTime))
.collect(Collectors.toList());

datetimes.forEach(datetime -> System.out.printf("%s %-12s %s\n", datetime, "(" + datetime.getDayOfWeek() + "):", !uptime.isUp(datetime)));

The output matches the expectation.



Update

A revision to the original post slightly changed the requirement. However,
you don't have to modify abovementioned code, as it'll still work if you modify your input. In fact, you are recording up-times instead of down-times. So instead, register your up-time times: Monday to Friday, 7:00 to 18:00.

Set<DayOfWeek> daysOfWeek = Set.of(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
LocalTime start = LocalTime.of(7, 0);
LocalTime end = LocalTime.of(18, 0);
Uptime uptime = new Uptime(daysOfWeek, start, end);

Now with uptime.isUp(LocalDateTime.now()) you can still check whether the system is up.

What is the proper way to remove the time part from java.util.Date?

A Date object holds a variable wich represents the time as the number of milliseconds since epoch. So, you can't "remove" the time part. What you can do is set the time of that day to zero, which means it will be 00:00:00 000 of that day. This is done by using a GregorianCalendar:

GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
gc.set(Calendar.HOUR_OF_DAY, 0);
gc.set(Calendar.MINUTE, 0);
gc.set(Calendar.SECOND, 0);
gc.set(Calendar.MILLISECOND, 0);
Date returnDate = gc.getTime();

How to cut time zone information in Java

You can use DateTimeFormatter.

  LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String text = date.format(formatter);

If you are using Java 8 it is better to use java.time.LocalDate. If you have to use java.util.Date you can still convert it to LocalDate.

Date now= new Date();
LocalDate date = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

Java Date Hibernate cut off time

I am not an expert with Oracle, but you probably need a DateTime column type to get a time stamp.

With that you need to use java.sql.Timestamp JDBC type.

Set time to 00:00:00

Use another constant instead of Calendar.HOUR, use Calendar.HOUR_OF_DAY.

calendar.set(Calendar.HOUR_OF_DAY, 0);

Calendar.HOUR uses 0-11 (for use with AM/PM), and Calendar.HOUR_OF_DAY uses 0-23.

To quote the Javadocs:

public static final int HOUR

Field number for get and set indicating
the hour of the morning or afternoon. HOUR is used for the 12-hour
clock (0 - 11). Noon and midnight are represented by 0, not by 12.
E.g., at 10:04:15.250 PM the HOUR is 10.

and

public static final int HOUR_OF_DAY

Field number for get and set
indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour
clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.

Testing ("now" is currently c. 14:55 on July 23, 2013 Pacific Daylight Time):

public class Main
{
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

public static void main(String[] args)
{
Calendar now = Calendar.getInstance();
now.set(Calendar.HOUR, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
System.out.println(sdf.format(now.getTime()));
now.set(Calendar.HOUR_OF_DAY, 0);
System.out.println(sdf.format(now.getTime()));
}
}

Output:

$ javac Main.java
$ java Main
2013-07-23 12:00:00
2013-07-23 00:00:00

How to check cutoff time before or after the current time instance?

Java 8 date/time api

LocalDateTime currentDateTime = LocalDateTime.now();
LocalDate currentDate = LocalDate.now();
String cutOff = "05:00 AM";
DateTimeFormatter timeParser = DateTimeFormatter.ofPattern("hh:mm a");
LocalTime cutOffTime = timeParser.parse(cutOff, LocalTime::from);
LocalDateTime cutOffDateTime = LocalDateTime.of(currentDate, cutOffTime);
//After
cutOffDateTime.isAfter(currentDateTime);
//Before
cutOffDateTime.isBefore(currentDateTime);
//Compare
cutOffDateTime.compareTo(currentDateTime);

How to set time to a date object in java

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,17);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);

Date d = cal.getTime();

Also See

  • Joda time
  • Calendar doc

How to truncate time on java.sql.Date?

Try this:

String dateCompleted = "4/24/2009 2:38:44 PM";
DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
java.util.Date tempDate = format.parse(dateCompleted);
java.sql.Date completionDate = new java.sql.Date(tempDate.getTime());

same as mentioned by @sgpalit.



Related Topics



Leave a reply



Submit