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();
6
  • Copy the code of SimpleDateFormat into your code?
    – clcto
    May 9, 2014 at 13:25
  • You can use Calendar and build the same String with "calendar.get(Calendar.HOUR) etc.
    – pL4Gu33
    May 9, 2014 at 13:28
  • 2
    ... what is the issue with the java.text package? It's a JRE package, after all.. May 9, 2014 at 13:28
  • It's for a univercity project and we must use only java.util.* May 9, 2014 at 13:29

1 Answer 1

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()));
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.