java get date marker field(am/pm)

后端 未结 5 1321
没有蜡笔的小新
没有蜡笔的小新 2021-01-12 04:07

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

This is my code.

String startTime =\"01:05 PM\";
 SimpleDateFormat sdf = new SimpleDa         


        
相关标签:
5条回答
  • 2021-01-12 04:46

    You could use a 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.

    0 讨论(0)
  • 2021-01-12 04:50

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

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

    The TimeZone caveat also applies here.

    0 讨论(0)
  • 2021-01-12 04:51

    Calendar can also do

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

    meridiem now equals "PM" based on your code.

    0 讨论(0)
  • 2021-01-12 04:54

    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()));
    
    0 讨论(0)
  • 2021-01-12 05:02

    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;
    
    }
    
    0 讨论(0)
提交回复
热议问题