Java基础——获取当前系统时间和上一天时间

来源:互联网 发布:mac与pc共享连接失败 编辑:程序博客网 时间:2024/06/04 19:51
java中获取当前日期和时间的方法
 

import java.util.Date;
import java.util.Calendar;

import java.text.SimpleDateFormat;

public class TestDate{
public static void main(String[] args){
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//可以方便地修改日期格式


String hehe = dateFormat.format( now );
System.out.println(hehe);

Calendar c = Calendar.getInstance();//可以对每个时间域单独修改

c.setTime(now);

now = c.getTime();//例如:2017-05-26


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);
System.out.println(year + "/" + month + "/" + date + " " +hour + ":" +minute + ":" + second);
}
}

获取上一天时间:

String fileTime = request.getParameter("fileTime");
        //日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字符串转日期
        Date fileDate = sdf.parse(fileTime);
        Calendar calendar = Calendar.getInstance();  
        calendar.setTime(fileDate);

//获取fileDate上一天
            calendar.add(Calendar.DAY_OF_MONTH, -1); 

//获取后一天

calendar.add(Calendar.DAY_OF_MONTH, 1);

           fileDate = calendar.getTime();  
            //日期转字符串
            fileTime = sdf.format(fileDate);

 有时候要把String类型的时间转换为Date类型,通过以下的方式,就可以将你刚得到的时间字符串转换为Date类型了。

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

java.util.Date time=null;
try {
   time= sdf.parse(sdf.format(new Date()));

} catch (ParseException e) {

   e.printStackTrace();
}

注意:月份从0开始到11表示1到12月份,Date跟Calendar获取的时间都是当前服务器所在的计算机的系统时间!

0 0