I am looking for a way to convert the datatype DATE [JAVA]
to a quarter of an hour format, so that
2010-08-15 12:05:15 will be 2010-08-15 12:00:00
Are there any ready to go methods in JAVA already?
How would you do this?
Any hints/suggestions?
I am looking for a way to convert the datatype DATE [JAVA]
to a quarter of an hour format, so that
2010-08-15 12:05:15 will be 2010-08-15 12:00:00
Are there any ready to go methods in JAVA already?
How would you do this?
Any hints/suggestions?
Use a Calendar object, then you can and manipulate the indvidual fields
int min = cal.get (Calendar.MINUTE);
int val = min / 15; // or what ever logic you have.
Up to release version 7, Java comes with a terrible date and time API. Many developers therefore choose to use Joda time instead. It is a very common third-party dependency in many projects.
Using Joda time, you can do the following:
Date toQuaterOfHour(Date date) {
LocalDateTime ldt = new LocalDateTime(date.getTime());
int quater = ldt.getMinuteOfHour() / 15;
return ldt.withMinuteOfHour(quater * 15).toDate();
}
Java 8 comes with a date and time API that is similar to that of Joda time.
First of all, joda-time is battle tested well known solution for working with date/times in Java, so if you can push it into your project, do it (or at least try).
Second, I can help you with that, but please put here fully qualified name of object you are using. Date in java.util is mostly deprecated, so I would suggest looking on GregorianCalendar object (included in JDK) for date/time manipulation.
You may use simple arithmetic like this:
long millis = 15 * 60 * 1000;
long now = System.currentTimeMillis();
long rest = now % millis;
long quarter = now + (rest == 0 ? 0 : rest >= millis / 2 ? millis - rest : -rest);
System.out.println("Original: " + new Date(now));
System.out.println("Quarter: " + new Date(quarter));
Use the class SimpleDateFormat and choose the output format of your choice.