在android中获取格式化的日期和时间

Ris*_*shi 4 android

我有两个函数来计算日期和时间.

  public static String getFormattedDate(String time) {
    long timeUnix = Long.parseLong(time);
    Date myDate = new Date(timeUnix * 1000);
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM d yy");
    return simpleDateFormat.format(myDate);
}

  public static String getFormattedTime(String time) {
    long timeUnix = Long.parseLong(time);
    Date myDate = new Date(timeUnix * 1000);
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss");
    return simpleDateFormat.format(myDate);
}
Run Code Online (Sandbox Code Playgroud)

我得到了他们需要的正确输出.

Jul 12 11(date function) and 12:09:45(time function)
Run Code Online (Sandbox Code Playgroud)

如何计算天数以及如何设置上午/下午.

如果它是今天的日期,我试图设定上午/下午的时间,如果它比显示日期(星期一,星期二,星期三等)更长,并且如果它比显示"MMM d yy"的时间长一周以上.

For*_*ega 11

对于am/pm表示法:

SimpleDateFormat dateFormat = new SimpleDateFormat("KK:mm:ss a");
return dateFormat.format(myDate);
Run Code Online (Sandbox Code Playgroud)

KK是上午/下午(0-11)的小时,而HH是一天中的小时(0-23)


小智 9

Calendar cal = Calendar.getInstance();
Date currentLocalTime = cal.getTime();

DateFormat date = new SimpleDateFormat("dd-MM-yyy HH:mm:ss z");

String localTime = date.format(currentLocalTime);

System.out.println(localTime);
Run Code Online (Sandbox Code Playgroud)