How to convert 24 hr format time in to 12 hr Format?
In my application i want to convert the given CDT formatted 24 hr string in to CDT formatted 12 hr string, How to开发者_如何学Python convert a given 24 hr format string in to 12 hr format string??
Here is the code to convert 24-Hour time to 12-Hour with AM and PM.
Note:- If you don't want AM/PM then just replace hh:mm a
with hh:mm
.
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String [] args) throws Exception {
try {
String _24HourTime = "22:15";
SimpleDateFormat _24HourSDF = new SimpleDateFormat("HH:mm");
SimpleDateFormat _12HourSDF = new SimpleDateFormat("hh:mm a");
Date _24HourDt = _24HourSDF.parse(_24HourTime);
System.out.println(_24HourDt);
System.out.println(_12HourSDF.format(_24HourDt));
} catch (Exception e) {
e.printStackTrace();
}
}
}
//OUTPUT WOULD BE
//Thu Jan 01 22:15:00 IST 1970
//10:15 PM
Another Solution:
System.out.println(hr%12 + ":" + min + " " + ((hr>=12) ? "PM" : "AM"));
you can try using a SimpleDateFormat
object to convert the time formats.
final String time = "23:15";
try {
final SimpleDateFormat sdf = new SimpleDateFormat("H:mm");
final Date dateObj = sdf.parse(time);
System.out.println(dateObj);
System.out.println(new SimpleDateFormat("K:mm").format(dateObj));
} catch (final ParseException e) {
e.printStackTrace();
}
here is the javadoc link for SimpleDateFromat.
In Java 8 it could be done in one line using class java.time.LocalTime
.
Code example:
String result = LocalTime.parse(time, DateTimeFormatter.ofPattern("HH:mm")).format(DateTimeFormatter.ofPattern("hh:mm a"));
For earlier Android, use the ThreeTen-Backport project, adapted for Android in the ThreeTenABP project. See How to use ThreeTenABP in Android Project.
For someone with lower api version, work well with 12:00 AM or PM and min < 10
String time = ((hourOfDay > 12) ? hourOfDay % 12 : hourOfDay) + ":" + (minute < 10 ? ("0" + minute) : minute) + " " + ((hourOfDay >= 12) ? "PM" : "AM")
output eg. 0:0 AM
12:00 PM
9:09 AM
thanks to @Lalit Jawale answer above
In case you are curious about the difference between K, k and H, h:
H Hour in day (0-23) Number 0 1+
k Hour in day (1-24) Number 24 1+
K Hour in am/pm (0-11) Number 0 1+
h Hour in am/pm (1-12) Number 12 1+
// time is your string value i.e., 24 hour time
try {
final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
final Date dateObj = sdf.parse(time);
time = new SimpleDateFormat("hh:mm aa").format(dateObj);
} catch (final ParseException e) {
e.printStackTrace();
}
SimpleDateFormat with (K:mm) works fine, but won't work properly with time 12:00 AM or 12:00 PM
You can use the above code to convert 12 hour format from 24 hour format along with AM/PM... It works
I don't like using classes like SimpleDateFormat
if it's not necessary. You just have to check three conditions. Here are some alternatives:
Simple:
if(hour>11) {
suffix = "PM";
if(hour>12)
hour -= 12;
} else {
suffix = "AM";
if(hour==0)
hour = 12;
}
Short:
suffix = (hour>11) ? "PM" : "AM";
hour = (hour>12) ? hour-=12 : ((hour==0) ? 12 : hour);
Result:
00:00 = 12:00 AM, 01:00 = 01:00 AM, 02:00 = 02:00 AM, 03:00 = 03:00 AM, 04:00 = 04:00 AM, 05:00 = 05:00 AM, 06:00 = 06:00 AM, 07:00 = 07:00 AM, 08:00 = 08:00 AM, 09:00 = 09:00 AM, 10:00 = 10:00 AM, 11:00 = 11:00 AM, 12:00 = 12:00 PM, 13:00 = 01:00 PM, 14:00 = 02:00 PM, 15:00 = 03:00 PM, 16:00 = 04:00 PM, 17:00 = 05:00 PM, 18:00 = 06:00 PM, 19:00 = 07:00 PM, 20:00 = 08:00 PM, 21:00 = 09:00 PM, 22:00 = 10:00 PM, 23:00 = 11:00 PM
in a clean way you can do this:
fun convertTo12Hours(militaryTime: String): String{
//in => "14:00:00"
//out => "02:00 PM"
val inputFormat = SimpleDateFormat("hh:mm:ss", Locale.getDefault())
val outputFormat = SimpleDateFormat("hh:mm aa", Locale.getDefault())
val date = inputFormat.parse(militaryTime)
return outputFormat.format(date)
}
int n=2;
int result= n-12;
if (result>o) {
system.out.println(result+"pm");
} else {
system.out.prinln(result+"am");
}
You can use Scanner if you want take input from user Hope this is simple 12 for time :)
Follow below code:
Make common method and call from where you need:
COMMON METHOD TO CHANGE TIME:
public static String parseTime(String date, String inFormat, String outFormat) {
try {
Date date1 = new SimpleDateFormat(inFormat, Locale.getDefault()).parse(date);
SimpleDateFormat dateFormat = new SimpleDateFormat(outFormat, Locale.getDefault());
return dateFormat.format(date1);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
CONSTANT METHOD:
public static final String SERVER_TIME_RESOURCES_FORMAT = "HH:mm:ss";
public static final String SERVER_TIME_FORMAT = "HH:mm:ss.SSS";
CALL FROM WHER U NEED:
CommonMethods.parseTime(//your date, Constants.SERVER_TIME_RESOURCES_FORMAT, Constants.LOCAL_TIME_FORMAT);
Here I use simple maths. 12Hours = 1 + currentHours(24Hours)-13. For AM & PM use simple ifelse condition, like if currentHours(24Hours) is <= 12 then set 'AM' or set 'PM' Here AMPM & Time is String varriable. CurHour is int.
LocalDateTime LDT = LocalDateTime.now();
CurHour = LDT.getHour();
if(CurHour <=12) {
AMPM = "AM";
}else {
AMPM = "PM";
}
Hours = 1+CurHour-13;
Time = Hours+":"+LDT.getMinute()+":"+LDT.getSecond()+" "+AMPM;
Here's my solution:
/*
* hour in 24Format -> AM/PM Format
*/
public String format(int hour, int minutes ){
String meridiem = hour > 11 ? "PM" : "AM";
// trim "0-23 hour" to "0-11 hour", then replace "0" with "12"
hour = (hour %= 12) == 0 ? 12 : hour;
// Apply desired format "HH:MM AM/PM"
return String.format("%02d:%02d %s", hour, minutes, meridiem );
}
public static void convert24HourTimeInto12Hour() {
try {
String[] dateTime = getCurrentDateAndTime("yyyy-MM-dd HH:mm:ss").split(" ");
System.out.println("datePart::: "+dateTime[0]);
System.out.println("timePart::: "+dateTime[1]);
SimpleDateFormat 24HoursFormat = new SimpleDateFormat
SimpleDateFormat 12HoursFormat = new SimpleDateFormat
Date 24Hours = 24HoursFormat.parse(dateTime[1]);
System.out.println(24Hours);
System.out.println(12HoursFormat.format(24Hours));
} catch (Exception e) {
e.printStackTrace();
}
}
For converting any Date date to 12 hour format with AM and PM you can use
new SimpleDateFormat("dd MMM yyyy KK:mm:ss a").format(date)
Here KK signifies 00-12 and a signifies AM and PM
This is what I have used, it converts 00:10 am to 12:00 am and the remaining also works fine.
int hourOfDay=Integer.parseInt(form24hrs);//parsing 24 hours format string value of hour to int
int minute=Integer.parseInt(form24min);//parsing 24 hours format string value of minute to int
String time = ((hourOfDay > 12) ? hourOfDay % 12 : ((hourOfDay==0)?"12":hourOfDay)) + ":" + (minute < 10 ? ("0" + minute) : minute) + " " + ((hourOfDay >= 12) ? "pm" : "am");
Kotlin version of @xianwei 's answer
val hourOfDay = timePicker.hour
val minute = timePicker.minute
val finalHour = (if (hourOfDay > 12) hourOfDay % 12 else hourOfDay).toString()
val finalMinute = if (minute < 10) "0$minute" else minute.toString()
val finalMeridian = if (hourOfDay > 12) "PM" else "AM"
val time = "$finalHour:$finalMinute $finalMeridian"
public static String convertYourTime(String time24) {
try {
SimpleDateFormat format24 = new SimpleDateFormat("HH:mm");
Date time = format24.parse(time24);
SimpleDateFormat format12 = new SimpleDateFormat("hh:mm a");
return format12.format(time);
} catch (ParseException e) {
// Handle invalid input
}
}
精彩评论