how to convert date and time to 12 hour format

强颜欢笑 提交于 2019-12-04 18:08:53

You need two formats: one to parse, and one to format. You need to parse from String to Date with one DateFormat, then format that Date into a String with the other format.

Currently, your single SimpleDateFormat is half way between - you've got HH which is 24-hour, but you've also got aa which is for am/pm. You want HH without the aa for input, and hh with the aa for output. (It's almost never appropriate to have both HH and aa.)

TimeZone utc = TimeZone.getTimeZone("etc/UTC");
DateFormat inputFormat = new SimpleDateFormat("dd MMM, yyyy HH:mm",
                                              Locale.US);
inputFormat.setTimeZone(utc);
DateFormat outputFormat = new SimpleDateFormat("dd MMM, yyyy hh:mm aa",
                                              Locale.US);
outputFormat.setTimeZone(utc);

Date date = inputFormat.parse(input);
String output = outputFormat.format(date);

Note that I'm setting the locale to US so it can always parse "Nov", and the time zone to UTC so you don't need to worry about certain times being skipped or ambiguous.

Amitsharma

try with this answer this is shortest and best answer on stack.

    Calendar c = Calendar.getInstance();
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss aa");
     Datetime = sdf.format(c.getTime());
     System.out.println("============="+Datetime);

Result:-=========2015-11-20 05:52:25 PM

try with this link Link here

Try understand SimpleDateFormat Symbol and Meaning :

 Symbol       Meaning
   H      hour in day (0-23)
   K      hour in am/pm (0-11)
   h      hour in am/pm (1-12)
   k      hour in day (1-24)

SimpleDateFormat  dateformat = new SimpleDateFormat("dd' 'MMM,' 'yyyy KK:mm aa");

OR

SimpleDateFormat  dateformat = new SimpleDateFormat("dd' 'MMM,' 'yyyy hh:mm aa");

Example:

convertDateStringFormat("12 Nov, 2014 23:13","dd MMM, yyyy HH:mm","dd MMM, yyyy hh:mm aa")

public String convertDateStringFormat(String strDate, String fromFormat, String toFormat){
   try{
       SimpleDateFormat sdf = new SimpleDateFormat(fromFormat);
       sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
       SimpleDateFormat dateFormat2 = new SimpleDateFormat(toFormat.trim());
       return dateFormat2.format(sdf.parse(strDate));
   }catch (Exception e) {
       e.printStackTrace();
       return "";
   }
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!