一文搞懂Java中Date和time

一文搞懂Java中Date和time

Date相关操作

  1. 构造方法
import java.util.Date;
public class Date_Learning {
    public static void main(String[] args) {
        //无参构造方法:获取当前系统时间
        Date currentTime=new Date();
        System.out.println("当前系统时间为"+currentTime);
        //使用指定的时间戳进行构造,也就是获取与基准时间间隔timeTamp的时间,单位是ms。
        Date baseTime=new Date(0);//当timeTamp=0的时候也就是基准时间
        System.out.println("基准时间为:"+baseTime);
        Date specific_time=new Date(1671408000000L);//计算器大概算了一下时间
        System.out.println("指定时间为"+specific_time);
    }
}

输出结果:

当前系统时间为Mon Jul 31 09:38:21 GMT+08:00 2023
基准时间为:Thu Jan 01 08:00:00 GMT+08:00 1970
指定时间为Mon Dec 19 08:00:00 GMT+08:00 2022
  1. 字符串和Date类型相互转化
  • Date转字符串
import java.text.SimpleDateFormat;
import java.util.Date;
public class Date_Learning {
    public static void main(String[] args) {
		Date currentDate = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = dateFormat.format(currentDate);
		System.out.println(dateString);
	}
}

输出结果:

2023-07-31 10:06:22
  • 字符串转Date
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Date_Learning {
    public static void main(String[] args) {
		String dateStr = "2023-07-31 10:06:22";
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
		    Date parsedDate = dateFormat.parse(dateStr);
		    System.out.println(parsedDate);
		} catch (ParseException e) {
		    e.printStackTrace();
		}
	}
}

输出结果:

Mon Jul 31 10:06:22 GMT+08:00 2023

PS:这是本人的第一篇CSDN blog,如有问题请指出!由于时间原因time的相关操作后续更新,相较而言Date已经过时了,多采用java8新的time包对日期时间进行操作,敬请期待!
2023年7月31日 10:10:41

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值