programing

AM/PM과 함께 현재 시간을 12시간 형식으로 표시

prostudy 2022. 5. 30. 22:01
반응형

AM/PM과 함께 현재 시간을 12시간 형식으로 표시

현재 시간은 13:35 PM으로 표시되지만 13:35 PM이 아닌 12시간 형식으로 AM/PM으로 표시하기를 원합니다.

현재 코드는 다음과 같습니다.

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";
}

날짜 패턴을 사용하여 가장 쉽게 얻을 수 있는 방법 -h:mm a,어디에

  • h - 오전/오후(1~12시)
  • m - 분(시)
  • a - AM/PM 마커

코드 스니펫:

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

자세한 내용은 설명서를 참조하십시오 - SimpleDateFormat Java 7

이것을 사용하다SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");

여기에 이미지 설명 입력

SimpleDateFormat용 Java 문서

사용하다"hh:mm a"대신"HH:mm a".여기서hh12시간 형식 및HH24시간 형식입니다.

라이브 데모

SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm:ss a");
  • h는 AM/PM 시간(1~12)에 사용됩니다.

  • H는 24시간(1~24) 동안 사용됩니다.

  • a는 AM/PM 마커입니다.

  • m은 분(시)입니다.

참고: 두 개의 h가 선행 0: 0 오후 1:13 으로 출력됩니다.선두 0을 제외한 1시간 인쇄: 오후 1시 13분.

기본적으로 모두가 이미 나보다 앞서고 있는 것 같은데, 난 딴 데로 새고 있어

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

출력: 11-Sep-13 12.25.15.375 PM

// 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())); 

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

AM과의 현재 시간을 원한다면 Android의 PM을 사용합니다.

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

현재 시간을 am과 함께 하려면 pm

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

또는

API 레벨 26부터

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

아래 문장을 대체하기만 하면 됩니다.

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

dr;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/PM에서 12시간제를 고집하는 대신 java.time이 자동으로 현지화되도록 하는 것이 좋습니다.를 호출합니다.

현지화하려면 다음을 지정합니다.

  • 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 ) ;

코드는 IdeOne.com에서 라이브로 실행됩니다.

10시 31분

오전 10:31

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

날짜와 시간이 표시됩니다.

    //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

현재 모바일 날짜 및 시간 형식을 입력하려면

2018년 2월 9일 10:36:59 PM

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

보여주시면 됩니다.Activity,Fragment,CardView,ListView「서나」를 하여, 의 장소에 구애받지 않습니다.TextView

` 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);

  `
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) {}
   }
}
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");

여기에는 SimpleDateFormat을 사용할 수 있습니다.

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

도움이 되시길 바랍니다.

언급URL : https://stackoverflow.com/questions/18734452/display-current-time-in-12-hour-format-with-am-pm

반응형