AM / PM을 사용하여 12 시간 형식으로 현재 시간 표시
현재 시간이 표시 13시 35분 오후 그러나 내가 즉, AM / PM 12 시간 형식, 1:35 PM 대신 13시 35분 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-오전 / 오후 마커
코드 스 니펫 :
DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
설명서에 대한 자세한 내용-SimpleDateFormat java 7
이것을 사용하십시오 SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");
"hh:mm a"
대신에 사용하십시오 "HH:mm a"
. 이곳까지 hh
12 시간 형식과 HH
24 시간 형식.
라이브 데모
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
SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm:ss a");
h는 AM / PM 시간 (1-12)에 사용됩니다.
H는 24 시간 (1-24) 동안 사용됩니다.
a는 AM / PM 마커입니다
m은 시간 단위입니다
Note: Two h's will print a leading zero: 01:13 PM. One h will print without the leading zero: 1:13 PM.
Looks like basically everyone beat me to it already, but I digress
// 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()));
Using Java 8:
LocalTime localTime = LocalTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
System.out.println(localTime.format(dateTimeFormatter));
The output is in AM/PM
Format.
Sample output: 3:00 PM
Just replace below statement and it will work.
SimpleDateFormat formatDate = new SimpleDateFormat("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
If you want current time with AM, PM in Android use
String time = new SimpleDateFormat("hh : mm a", Locale.getDefault()).format(Calendar.getInstance().getTime());
If you want current time with am, pm
String time = new SimpleDateFormat("hh : mm a", Locale.getDefault()).format(Calendar.getInstance().getTime()).toLowerCase();
OR
From API level 26
LocalTime localTime = LocalTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
String time = localTime.format(dateTimeFormatter);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
This will display the date and time
tl;dr
Let the modern java.time classes of JSR 310 automatically generate localized text, rather than hard-coding 12-hour clock and 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
Automatically localize
Rather than insisting on 12-hour clock with AM/PM, you may want to let java.time automatically localize for you. Call DateTimeFormatter.ofLocalizedTime
.
To localize, specify:
FormatStyle
to determine how long or abbreviated should the string be.Locale
to determine:- The human language for translation of name of day, name of month, and such.
- The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Here we get the current time-of-day as seen in a particular time zone. Then we generate text to represent that time. We localize to French language in Canada culture, then English language in US culture.
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 ) ;
See this code run live at IdeOne.com.
10 h 31
10:31 AM
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
To put your current mobile date and time format in
Feb 9, 2018 10:36:59 PM
Date date = new Date();
String stringDate = DateFormat.getDateTimeInstance().format(date);
you can show it to your Activity
, Fragment
, CardView
, ListView
anywhere by using 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) {}
}
}
You can use SimpleDateFormat for this.
SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");
Hope this helps you.
참고 URL : https://stackoverflow.com/questions/18734452/display-current-time-in-12-hour-format-with-am-pm
'Programing' 카테고리의 다른 글
# 1273-알 수없는 데이터 정렬 : 'utf8mb4_unicode_ci'cPanel (0) | 2020.05.31 |
---|---|
C ++ for 루프 전에는 본 적이 없다 (0) | 2020.05.31 |
ID가 #### 인 프로세스가 Visual Studio Professional 2013 업데이트 3에서 실행되고 있지 않습니다. (0) | 2020.05.31 |
현재 위치 권한 대화 상자가 너무 빨리 사라짐 (0) | 2020.05.31 |
3/4가 참인지 테스트하는 논리 (0) | 2020.05.31 |