以下代码获取日期:
private static String get_date() {
return (new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")).format(Calendar.getInstance().getTime());
}
使用import java.text.SimpleDateFormat;
如何仅使用import java.util.*;
这样做可以吗?为什么我收到警告?
Date date= new java.util.Date();
String s = (date.getYear()+1900)+"/"+date.getMonth()+"/"+date.getDay()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
答案 0 :(得分:1)
String.format()是你的朋友。
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()));
}