1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
/* Formatting hour using SimpleDateFormat This example shows how to format hour field using Java SimpleDateFormat class. Hour can be formatted in H, HH, h, hh, k, kk, K and KK formats. */ import java.text.SimpleDateFormat; import java.util.Date; public class FormattingHour { public static void main(String[] args) { //create Date object Date date = new Date(); //formatting hour in h (1-12 in AM/PM) format like 1, 2..12. String strDateFormat = "h"; SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat); System.out.println("hour in h format : " + sdf.format(date)); //formatting hour in hh (01-12 in AM/PM) format like 01, 02..12. strDateFormat = "hh"; sdf = new SimpleDateFormat(strDateFormat); System.out.println("hour in hh format : " + sdf.format(date)); //formatting hour in H (0-23) format like 0, 1...23. strDateFormat = "H"; sdf = new SimpleDateFormat(strDateFormat); System.out.println("hour in H format : " + sdf.format(date)); //formatting hour in HH (00-23) format like 00, 01..23. strDateFormat = "HH"; sdf = new SimpleDateFormat(strDateFormat); System.out.println("hour in HH format : " + sdf.format(date)); //formatting hour in k (1-24) format like 1, 2..24. strDateFormat = "k"; sdf = new SimpleDateFormat(strDateFormat); System.out.println("hour in k format : " + sdf.format(date)); //formatting hour in kk (01-24) format like 01, 02..24. strDateFormat = "kk"; sdf = new SimpleDateFormat(strDateFormat); System.out.println("hour in kk format : " + sdf.format(date)); //formatting hour in K (0-11 in AM/PM) format like 0, 1..11. strDateFormat = "K"; sdf = new SimpleDateFormat(strDateFormat); System.out.println("hour in K format : " + sdf.format(date)); //formatting hour in KK (00-11) format like 00, 01,..11. strDateFormat = "KK"; sdf = new SimpleDateFormat(strDateFormat); System.out.println("hour in KK format : " + sdf.format(date)); } } /* Typical output would be hour in h format : 12 hour in hh format : 12 hour in H format : 0 hour in HH format : 00 hour in k format : 24 hour in kk format : 24 hour in K format : 0 hour in KK format : 00 */ |
Add Comment