java获取日期标记字段(上午/下午)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2323964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:09:02  来源:igfitidea点击:

java get date marker field(am/pm)

java

提问by Srinivasan

I need to get the field AM/PM in date object. How can i get it?

我需要在日期对象中获取字段 AM/PM。我怎么才能得到它?

This is my code.

这是我的代码。

String startTime ="01:05 PM";
 SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");

 Date st = sdf.parse(startTime);

采纳答案by cletus

You could use a Calendar.

你可以使用一个Calendar.

Calendar cal = Calendar.getInstance();
cal.setTime(st);
if (cal.get(Calendar.AM_PM) == Calendar.PM) {
  ...
}

Make sure you don't have a time zone mismatch when you do this.

确保您在执行此操作时没有时区不匹配。

回答by Thilo

Calendar is probably best, but you could use DateFormat, too:

Calendar 可能是最好的,但您也可以使用 DateFormat:

String amPm = new SimpleDateFormat("aa").format(time);

The TimeZone caveat also applies here.

时区警告也适用于此。

回答by Nitin Karale

Please try this

请试试这个

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss_aa");
    Calendar cal = Calendar.getInstance();
    Log.d("Time", ""+dateFormat.format(cal.getTime()));
    int day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
    System.out.println("time => " + namesOfDays[day-1]+"_"+dateFormat.format(cal.getTime()));

回答by Kishan Vaghela

use this..

用这个..

String getTime(String milliseconds) {

    String time = "";
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(Long.parseLong(milliseconds));

    time = cal.get(Calendar.HOUR) + " : " + cal.get(Calendar.MINUTE);

    if(cal.get(Calendar.AM_PM)==0)
        time=time+" AM";
    else
        time=time+" PM";

    return time;

}

回答by Nathan Reline

Calendarcan also do

Calendar也可以做

Calendar cal = Calendar.getInstance();
cal.setTime(st);
String meridiem = cal.getDisplayName(Calendar.AM_PM, Calendar.SHORT, Locale.getDefault())

meridiemnow equals "PM" based on your code.

meridiem现在根据您的代码等于“PM”。