You can use getters java.time.LocalDateTime .
LocalDateTime now = LocalDateTime.now(); int year = now.getYear(); int month = now.getMonthValue(); int day = now.getDayOfMonth(); int hour = now.getHour(); int minute = now.getMinute(); int second = now.getSecond(); int millis = now.get(ChronoField.MILLI_OF_SECOND); // Note: no direct getter available. System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);
Or, if you are not already in Java 8, use java.util.Calendar .
Calendar now = Calendar.getInstance(); int year = now.get(Calendar.YEAR); int month = now.get(Calendar.MONTH) + 1; // Note: zero based! int day = now.get(Calendar.DAY_OF_MONTH); int hour = now.get(Calendar.HOUR_OF_DAY); int minute = now.get(Calendar.MINUTE); int second = now.get(Calendar.SECOND); int millis = now.get(Calendar.MILLISECOND); System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);
In any case, this is printing at the moment:
2010-04-16 15: 15: 17.816
To convert int to String , use String#valueOf() .
If your intention is to arrange and display them in a friendly human format, then it is better to use either Java8 java.time.format.DateTimeFormatter ( tutorial here ),
LocalDateTime now = LocalDateTime.now(); String format1 = now.format(DateTimeFormatter.ISO_DATE_TIME); String format2 = now.atZone(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME); String format3 = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.ENGLISH)); System.out.println(format1); System.out.println(format2); System.out.println(format3);
or when you are not already in Java 8, use java.text.SimpleDateFormat :
Date now = new Date(); // java.util.Date, NOT java.sql.Date or java.sql.Timestamp! String format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(now); String format2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH).format(now); String format3 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH).format(now); System.out.println(format1); System.out.println(format2); System.out.println(format3);
In any case, this gives:
2010-04-16T15: 15: 17.816
Fri, 16 Apr 2010 15:15:17 GMT
20100416151517
See also:
- Convert strings to string in format