常用的获取当前时间的几种方法:

1. 获取当前时间

//方法一
long startTime = System.currentTimeMillis();
Timestamp now1 = new Timestamp(startTime);
System.out.println("now1:" + now1);
//方法二
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
String now3 = df.format(System.currentTimeMillis());   
System.out.println("now3:" + now3);
//方法三
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);
int millisecond = c.get(Calendar.MILLISECOND);
String now4 = year + "-" + month + "-" + date + " " +hour + ":" +minute + ":" + second + ":" + millisecond;
System.out.println("now4:" + now4);
//方法四
Date queueDate = new Date();
SimpleDateFormat queueDateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
String now2 = queueDateFormat.format(queueDate);
System.out.println("now2:" + now2);
//若获取的时间有误差,加时区
SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
simple.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
String now5 = simple.format(new Date());
System.out.println("now5:" + now5);

2. 获取半小时之后的时间

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
long currentTime = System.currentTimeMillis();
currentTime += 30 * 60 * 1000;
Date date = new Date(currentTime);
String endDate = df.format(date);

3. 获取当前日期及前后日期

Date now = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
//后一天日期+1,前一天日期-1
calendar.add(Calendar.DATE, +1);
Date oneDayAfter = calendar.getTime();
SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
simple.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
//当前日期
String nowDate = simple.format(now);
//当前日期后一天日期
String oneDayAfterDate = simple.format(oneDayAfter);
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐