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

半世苍凉 提交于 2019-12-01 09:24:01

问题


Calendar ci = Calendar.getInstance();

CiDateTime = "" + (ci.get(Calendar.MONTH) + 1) +  
    "/" + ci.get(Calendar.DAY_OF_MONTH) + 
    "/" + ci.get(Calendar.YEAR);

String visitdatetime = CiDateTime + "" + 
          ci.get(Calendar.HOUR_OF_DAY) + ":" + 
          ci.get(Calendar.MINUTE) + ":" + 
          ci.get(Calendar.SECOND);

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy  hh:mm  a");

I am getting from the server in 24 hours format.but want to show my date like MM/dd/yyyy hh:mm AM/PM like 12 hrs format.


回答1:


Did you try this ?

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



回答2:


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
}



回答3:


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



回答4:


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




回答5:


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



回答6:


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'"




回答7:


use below format to 12 hour with am/pm

MM/dd/yyyy HH:mm:ss a



来源:https://stackoverflow.com/questions/9532463/how-can-i-change-date-from-24-hours-format-to-12-hours-format-am-pm-in-android

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