2

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?

CodeFanatic
  • 11,434
  • 1
  • 20
  • 38

4 Answers4

3

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.
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
2

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.

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
  • Basically. The migration should be rather easy due to the similarity of the APIs. Package-wise, Joda time and the new Java time API live in different name spaces. Also, some of the methods have different names as visible from: http://download.java.net/jdk8/docs/api/java/time/LocalDateTime.html - An example would be the method `withMinute` instead of `withMinuteOfHour`. – Rafael Winterhalter Mar 06 '14 at 08:09
0

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.

apocalypz
  • 1,180
  • 1
  • 8
  • 11
0

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.

Harmlezz
  • 7,972
  • 27
  • 35