I would like to have them as strings.
views:
629answers:
5How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?
Look at the API documentation for the java.util.Calendar class and its derivatives (you may be specifically interested in the GregorianCalendar class).
Make use of java.util.Calendar
.
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH); // 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 + 1, day, hour, minute, second, millis);
This prints as of now (I'm at GMT-4):
2010-04-16 11:15:17.816
To convert an int
to String
, make use of String#valueOf()
.
If your intent is after all to arrange and display them in a human friendly format, then I'd suggest to use java.text.SimpleDateFormat
instead. Click the link, you'll see a table of patterns letters. Several examples:
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.SSSZ").format(now);
String format2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z").format(now);
String format3 = new SimpleDateFormat("yyyyMMddHHmmss").format(now);
System.out.println(format1);
System.out.println(format2);
System.out.println(format3);
Which yields:
2010-04-16T11:15:17.816-0400 Fri, 16 Apr 2010 11:15:17 -0400 20100416111517
Switch to joda-time and you can do this in three lines
DateTime jodaTime = new DateTime();
DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS");
System.out.println("jodaTime = " + formatter.print(jodaTime));
You also have direct access to the individual fields of the date without using a Calendar.
System.out.println("year = " + jodaTime.getYear());
System.out.println("month = " + jodaTime.getMonthOfYear());
System.out.println("day = " + jodaTime.getDayOfMonth());
System.out.println("hour = " + jodaTime.getHourOfDay());
System.out.println("minute = " + jodaTime.getMinuteOfHour());
System.out.println("second = " + jodaTime.getSecondOfMinute());
System.out.println("millis = " + jodaTime.getMillisOfSecond());
Output is as follows:
jodaTime = 2010-04-16 18:09:26.060
year = 2010
month = 4
day = 16
hour = 18
minute = 9
second = 26
millis = 60
Calendar now = new Calendar() // or new GregorianCalendar(), or whatever flavor you need
now.MONTH now.HOUR
etc.