1

I want to convert:

 Tue Mar 28 12:00:00 IST 2016 time format
     INTO
 Tue Mar 28 00:00:00 IST 2016

How can I do it?

=================
Actually In the database, my date is saved with the format of "Tue Mar 28 00:00:00 IST 2016", I want to fetch this record using this date.but my following code

Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.clear(Calendar.MILLISECOND);
        return calendar.getTime();

but this is giving me Tue Mar 28 12:00:00 IST 2016, whereas I want Mar 28 00:00:00 IST 2016, So that it would be same as Database one, and will fetch.

Abhishek Singh
  • 1,367
  • 1
  • 22
  • 46
  • 2
    Possible duplicate of [Adding n hours to a date in Java?](http://stackoverflow.com/questions/3581258/adding-n-hours-to-a-date-in-java) – scrappedcola Mar 28 '16 at 15:12
  • Wait, is that really 12 hours ahead of time or is that converting from 24 hours time format to 12 hours time format? If the latter, don't forget the AM/PM suffix... – fge Mar 28 '16 at 15:14
  • I update my question, wait – Abhishek Singh Mar 28 '16 at 15:18

3 Answers3

2

You need Calendar.HOUR_OF_DAY constant, which is used to operate in 24-hour clock, instead of Calendar.HOUR:

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0); // <-- here
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.clear(Calendar.MILLISECOND);
Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
1

You can just add 12 hours to date object, with calendar, e.g.:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse("2016-03-28");
System.out.println(date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR, 12);
System.out.println(calendar.getTime());
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
0

I think the OP wants to format the 24H time to 12H.

Try something like this:

SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");

Adam Rice
  • 880
  • 8
  • 20