How can I change date from 24-hours format to 12-hours format (am/pm) in android

巧了我就是萌 提交于 2019-12-01 10:29:58

Did you try this ?

SimpleDateFormat dateFromat= new SimpleDateFormat("MM/dd/yyyy  hh:mm  aa");
Date today = new Date();
String todayStr = dateFromat.format(today);

Below function may be useful to you. This will convert time from 24 hours to 12 hours

public static String Convert24to12(String time)
{
    String convertedTime ="";
    try {
        SimpleDateFormat displayFormat = new SimpleDateFormat("hh:mm a");
        SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm:ss");
        Date date = parseFormat.parse(time);        
        convertedTime=displayFormat.format(date);
        System.out.println("convertedTime : "+convertedTime);
    } catch (final ParseException e) {
        e.printStackTrace();
    }
    return convertedTime;
    //Output will be 10:23 PM
}
public static final String TIME_FORMAT = "hh:mm aa";
SimpleDateFormat TimeFormat = new SimpleDateFormat(TIME_FORMAT);

Calendar ATime = Calendar.getInstance();
String Timein12hourFormat = TimeFormat.format(ATime.getTime());

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

Stuart Smith

Here is the answer to get a data in US-English Format date/time using a 12 hour clock.

DateTime.Now.ToString("MM/d/yyyy hh:mm:ss tt");
01/16/2014 03:53:57 PM

hh:mm a

Adding the 'a' should do the trick in displaying the am/pm

In angular i am using angular-bootsrap-datetimepicker and to display the selected date and time i am using this syntax

data-ng-model="event.start | date:'dd-MM-yyyy hh:mm a'"

use below format to 12 hour with am/pm

MM/dd/yyyy HH:mm:ss a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!