使用AM / PM以12小时格式显示当前时间

时间:2013-09-11 06:48:24

标签: java date-format

目前时间显示为 13:35 PM 然而我想用AM / PM显示为12小时格式,即下午1:35而不是下午13:35

目前的代码如下

private static final int FOR_HOURS = 3600000;
private static final int FOR_MIN = 60000;
public String getTime(final Model model) {
    SimpleDateFormat formatDate = new SimpleDateFormat("HH:mm a");
    formatDate.setTimeZone(userContext.getUser().getTimeZone());
    model.addAttribute("userCurrentTime", formatDate.format(new Date()));
    final String offsetHours = String.format("%+03d:%02d", userContext.getUser().getTimeZone().getRawOffset()
    / FOR_HOURS, Math.abs(userContext.getUser().getTimeZone().getRawOffset() % FOR_HOURS / FOR_MIN));
    model.addAttribute("offsetHours",
                offsetHours + " " + userContext.getUser().getTimeZone().getDisplayName(Locale.ROOT));
    return "systemclock";
}

16 个答案:

答案 0 :(得分:394)

使用日期模式获取它的最简单方法 - h:mm a,其中

  • h - 上午/下午(1-12)小时
  • m - 小时分钟
  • a - Am / pm marker

代码段:

DateFormat dateFormat = new SimpleDateFormat("hh:mm a");

Read more on documentation - SimpleDateFormat java 7

答案 1 :(得分:101)

使用此SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");

enter image description here

Java docs for SimpleDateFormat

答案 2 :(得分:54)

使用"hh:mm a"代替"HH:mm a"。这里hh为12小时格式,HH为24小时格式。

直播Demo

答案 3 :(得分:18)

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.S aa");
String formattedDate = dateFormat.format(new Date()).toString();
System.out.println(formattedDate);

输出:     11月11日至12月12日15.25.15.375

答案 4 :(得分:13)

"CREATE TABLE `employee` (
  `id` int(6) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
  `username` varchar(15) NOT NULL ,
  `password` varchar(50) NOT NULL,
  `first_name` varchar(50) NOT NULL,
  `last_name` varchar(45) NOT NULL,
  `email` varchar(50) NOT NULL,
  `role` varchar(10) NOT NULL,
  'date_created' DATETIME NOT NULL DEFAULT GETDATE(),
   UNIQUE (id)
) ";
  • h用于AM / PM时间(1-12)。

  • H使用24小时(1-24)。

  • a是AM / PM标记

  • m是分钟

注意:两个小时将打印一个前导零:01:13 PM。一个h将打印没有前导零:下午1:13。

看起来基本上每个人都已经把它打败了,但我离题了

答案 5 :(得分:7)

// hh:mm will print hours in 12hrs clock and mins (e.g. 02:30)
System.out.println(DateTimeFormatter.ofPattern("hh:mm").format(LocalTime.now()));

// HH:mm will print hours in 24hrs clock and mins (e.g. 14:30)
System.out.println(DateTimeFormatter.ofPattern("HH:mm").format(LocalTime.now())); 

// hh:mm a will print hours in 12hrs clock, mins and AM/PM (e.g. 02:30 PM)
System.out.println(DateTimeFormatter.ofPattern("hh:mm a").format(LocalTime.now())); 

答案 6 :(得分:6)

只需替换以下声明即可。

SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");

答案 7 :(得分:6)

使用Java 8:

LocalTime localTime = LocalTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
System.out.println(localTime.format(dateTimeFormatter));

输出为AM/PM格式。

Sample output:  3:00 PM

答案 8 :(得分:3)

    //To get Filename + date and time


    SimpleDateFormat f = new SimpleDateFormat("MMM");
    SimpleDateFormat f1 = new SimpleDateFormat("dd");
    SimpleDateFormat f2 = new SimpleDateFormat("a");

    int h;
         if(Calendar.getInstance().get(Calendar.HOUR)==0)
            h=12;
         else
            h=Calendar.getInstance().get(Calendar.HOUR)

    String filename="TestReport"+f1.format(new Date())+f.format(new Date())+h+f2.format(new Date())+".txt";


The Output Like:TestReport27Apr3PM.txt

答案 9 :(得分:2)

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a");

这将显示日期和时间

答案 10 :(得分:2)

如果要使用 Android 中的AM,PM当前时间,请使用

String time = new SimpleDateFormat("hh : mm a", Locale.getDefault()).format(Calendar.getInstance().getTime());

如果您希望将当前时间设为上午pm

String time = new SimpleDateFormat("hh : mm a", Locale.getDefault()).format(Calendar.getInstance().getTime()).toLowerCase();

OR

从API级别26开始

LocalTime localTime = LocalTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
String time = localTime.format(dateTimeFormatter);

答案 11 :(得分:1)

tl; dr

让JSR 310的现代 java.time 类自动生成本地化文本,而不是硬编码12小时时钟和AM / PM。

LocalTime                                     // Represent a time-of-day, without date, without time zone or offset-from-UTC.
.now(                                         // Capture the current time-of-day as seen in a particular time zone.
    ZoneId.of( "Africa/Casablanca" )          
)                                             // Returns a `LocalTime` object.
.format(                                      // Generate text representing the value in our `LocalTime` object.
    DateTimeFormatter                         // Class responsible for generating text representing the value of a java.time object.
    .ofLocalizedTime(                         // Automatically localize the text being generated.
        FormatStyle.SHORT                     // Specify how long or abbreviated the generated text should be.
    )                                         // Returns a `DateTimeFormatter` object.
    .withLocale( Locale.US )                  // Specifies a particular locale for the `DateTimeFormatter` rather than rely on the JVM’s current default locale. Returns another separate `DateTimeFormatter` object rather than altering the first, per immutable objects pattern.
)                                             // Returns a `String` object.
  

10:31 AM

自动本地化

您可能不想让 java.time 为您自动本地化,而不是坚持使用AM / PM的12小时制。致电DateTimeFormatter.ofLocalizedTime

要本地化,请指定:

  • FormatStyle来确定字符串应该是多长时间或缩写。
  • Locale确定:
    • 用于翻译日名,月名等的人类语言
    • 文化规范决定缩写,大写,标点,分隔符等问题。

在这里,我们获得了在特定时区中看到的当前时间。然后,我们生成表示该时间的文本。我们将加拿大文化本地化为法语,然后将美国文化本地化为英语。

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalTime localTime = LocalTime.now( z ) ;

// Québec
Locale locale_fr_CA = Locale.CANADA_FRENCH ;  // Or `Locale.US`, and so on.
DateTimeFormatter formatterQuébec = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale_fr_CA ) ;
String outputQuébec = localTime.format( formatterQuébec ) ;

System.out.println( outputQuébec ) ;

// US
Locale locale_en_US = Locale.US ;  
DateTimeFormatter formatterUS = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale_en_US ) ;
String outputUS = localTime.format( formatterUS ) ;

System.out.println( outputUS ) ;

请参阅此code run live at IdeOne.com

  

10 h 31

     

10:31 AM

答案 12 :(得分:0)

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");

答案 13 :(得分:0)

将您当前的移动日期和时间格式设置为

  

2018年2月9日下午10:36:59

Date date = new Date();
 String stringDate = DateFormat.getDateTimeInstance().format(date);

您可以使用Activity

在任何地方向FragmentCardViewListViewTextView展示
` TextView mDateTime;

  mDateTime=findViewById(R.id.Your_TextViewId_Of_XML);

  Date date = new Date();
  String mStringDate = DateFormat.getDateTimeInstance().format(date);
  mDateTime.setText("My Device Current Date and Time is:"+date);

  `

答案 14 :(得分:0)

import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;

public class Main {
   public static void main(String [] args){
       try {
            DateFormat parseFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm a");
            String sDate = "22-01-2019 13:35 PM";
            Date date = parseFormat.parse(sDate);
            SimpleDateFormat displayFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
            sDate = displayFormat.format(date);
            System.out.println("The required format : " + sDate);
        } catch (Exception e) {}
   }
}

答案 15 :(得分:-2)

您可以使用SimpleDateFormat。

SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");

希望这会对你有所帮助。

相关问题