Java中Date类常见用法

Java中Date类的方法很多,要学会熟练运用JDK API文档。

文档下载:https://blog.youkuaiyun.com/BlueAndBug/article/details/103885595

import java.util.Date;
import java.text.SimpleDateFormat;
public class DateGet {

	public static void main(String[] args) throws Exception{
		//获取系统当前时间
		Date now=new Date();
		//两种方法相同
		System.out.println(now.getTime());
		System.out.println(System.currentTimeMillis());
		
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
		//格式化(将Date转换成String)
		String strTime=sdf.format(now);
		System.out.println(strTime);
		
		//String转换成Date
		String strTime1="2008-08-08 08:08:08 888";
		Date t=sdf.parse(strTime1);
		System.out.println(t);
	}

}
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateGet2 {
	public static void main(String[] args) {
		//获取当前时间的前十分钟的时间
		Date t1=new Date(System.currentTimeMillis()-1000*60*10);
		Date t2=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
		System.out.println(sdf.format(t1));
		System.out.println(sdf.format(t2));
	}
}
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class GetCalender {

	public static void main(String[] args) throws Exception {
		//获取当前日历 
		Calendar c=Calendar.getInstance();
		int i=c.get(Calendar.DAY_OF_WEEK);
		System.out.println("这是美国的第"+i+"天");
		//获取2008年8月8日是周几?
		String strTime="2008-8-8";
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		Date d=sdf.parse(strTime);
		c.setTime(d);
		System.out.println(c.get(Calendar.DAY_OF_WEEK));
	}

}

Java中,`java.util.Date`是用来处理日期和时间的对象,它表示自1970年1月1日(UTC/GMT的午夜)以来的毫秒数。以下是`Date`的一些常见用法: 1. **创建Date对象**: ```java Date date = new Date(); ``` 或者指定特定的时间戳: ```java long timestamp = System.currentTimeMillis(); // 获取当前系统时间的毫秒数 Date date = new Date(timestamp); ``` 2. **获取Date信息**: - 年、月、日、小时、分钟、秒和毫秒: ```java int year = date.getYear() + 1900; // 注意getYear返回的是从1900年开始的年份 int month = date.getMonth() + 1; int day = date.getDate(); int hour = date.getHours(); int minute = date.getMinutes(); int second = date.getSeconds(); int millisecond = date.getMilliseconds(); ``` - 使用`SimpleDateFormat`将Date转换为字符串格式: ```java SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formattedDate = sdf.format(date); ``` 3. **操作时间差**: ```java long diffInMilliseconds = Math.abs(new Date().getTime() - someOtherDate.getTime()); ``` 4. **比较两个Date对象**: ```java if (date.before(anotherDate)) { System.out.println("date is before anotherDate"); } ``` 5. **与Calendar结合使用**: `java.util.Calendar`提供更丰富的日期操作,比如设置特定的日期和时间。 注意:`Date`已过时,推荐使用`java.time`包中的`LocalDate`、`LocalTime`和`ZonedDateTime`等替换,它们有更好的API和更好的性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值