java 获取当前时间
获取当前日期和时间:
方法一:
import java.util.Date;
import java.text.SimpleDateFormat;
...
...
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = dateFormat.format(date);
方法二:
import java.util.Calendar;
...
...
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
String time = year + "/" + month + "/" + date + " " +hour + ":" +minute + ":" + second;
方法三:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.format(System.currentTimeMillis())
补充:
有时候要把String类型的时间转换为Date类型,如下:
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date time=null;
try {
time= sdf.parse(sdf.format(new Date()));
} catch (ParseException e) {
e.printStackTrace();
}
小结:
两种方法都可以满足需求,个人比较喜欢用方法一。
后语:
初出茅庐,如有不足,请留言赐教。
还没有评论,来说两句吧...