How can I change date from 24-hours format to 12-h

2020-03-28 02:18发布

问题:

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