1

The following code gets the date:

private static String get_date() {
    return (new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")).format(Calendar.getInstance().getTime());
}

using import java.text.SimpleDateFormat;

How can I do the above only by using a import java.util.*;

Is it okay to do it like this? Why I get warnings?

Date date= new java.util.Date();
        String s = (date.getYear()+1900)+"/"+date.getMonth()+"/"+date.getDay()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
  • Copy the code of `SimpleDateFormat` into your code? – clcto May 09 '14 at 13:25
  • You can use Calendar and build the same String with "calendar.get(Calendar.HOUR) etc. – pL4Gu33 May 09 '14 at 13:28
  • 2
    ... what is the issue with the java.text package? It's a JRE package, after all.. – Tassos Bassoukos May 09 '14 at 13:28
  • It's for a univercity project and we must use only java.util.* – user3620414 May 09 '14 at 13:29
  • http://stackoverflow.com/questions/2654025/how-to-get-year-month-day-hours-minutes-seconds-and-milliseconds-of-the-cur – Manuel Allenspach May 09 '14 at 13:49
  • As to why you are getting warnings, those methods you are using are deprecated -- they have been marked for destruction and even though they might work, eventually they will not be supported. I'm thinking your professor will not accept their use. (Then again, your professor requiring you to not use anything outside of java.util is... funny.) – James Dunn May 09 '14 at 14:01

1 Answers1

1

String.format() is your friend.

public static String formatDate(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    String template = "%04d/%02d/%02d %02d:%02d:%02d";
    return String.format(template, cal.get(Calendar.YEAR),
        cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH),
        cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE),
        cal.get(Calendar.SECOND));
}

public static void main(String[] args) {
    System.out.println(formatDate(new Date()));
}
James Dunn
  • 8,064
  • 13
  • 53
  • 87