简体   繁体   中英

Date conversion from 12:00:00 to 00:00:00 java

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.

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);

You can just add 12 hours to date object, with calendar , eg:

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());

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

Try something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM