Java中的Timestamp类型怎么赋值?

1.废话不多说先看代码:

 Timestamp time =  new Timestamp(122,6,4,18,12,57,0);

这个代表的时间是:

2022-07-04 18:12:57

至于为什么是这么多,读后面的解释你就知道了。

 2.解释

这个方法是被弃用了的,其定义为:

public class Timestamp extends java.util.Date {

    /**
     * Constructs a <code>Timestamp</code> object initialized
     * with the given values.
     *
     * @param year the year minus 1900
     * @param month 0 to 11
     * @param date 1 to 31
     * @param hour 0 to 23
     * @param minute 0 to 59
     * @param second 0 to 59
     * @param nano 0 to 999,999,999
     * @deprecated instead use the constructor <code>Timestamp(long millis)</code>
     * @exception IllegalArgumentException if the nano argument is out of bounds
     */
    @Deprecated
    public Timestamp(int year, int month, int date,
                     int hour, int minute, int second, int nano) {
        super(year, month, date, hour, minute, second);
        if (nano > 999999999 || nano < 0) {
            throw new IllegalArgumentException("nanos > 999999999 or < 0");
        }
        nanos = nano;
    }

 这个方法简单易懂,需要注意的就是每个参数的默认范围:

1)year – the year minus 1900

这里年份的最小值是1900年,这里的参数year是存的相对于1900年的偏移量,没错!是偏移量,不是单纯的年份,所以第一部分给出的122才会是对应于1900+122 = 2022年!

2)month,minute,second参数的范围

month参数的范围是从0开始算的,和数组下标类似,所以0代表的是1月,1代表的是2月,所以第一部分的6代表的才是7月,minute和second类似

3)只有date是从1正经开始的

3.关于该方法的补充说明

该方法已弃用,也就是不推荐使用,转而推荐使用都是是这个方法:

    /**
     * Constructs a <code>Timestamp</code> object
     * using a milliseconds time value. The
     * integral seconds are stored in the underlying date value; the
     * fractional seconds are stored in the <code>nanos</code> field of
     * the <code>Timestamp</code> object.
     *
     * @param time milliseconds since January 1, 1970, 00:00:00 GMT.
     *        A negative number is the number of milliseconds before
     *         January 1, 1970, 00:00:00 GMT.
     * @see java.util.Calendar
     */
    public Timestamp(long time) {
        super((time/1000)*1000);
        nanos = (int)((time%1000) * 1000000);
        if (nanos < 0) {
            nanos = 1000000000 + nanos;
            super.setTime(((time/1000)-1)*1000);
        }
    }

怎么说呢?就是让你输入一个long,这个long代表的是你想要设置的时间距1970, 00:00:00 GMT这个时间的毫秒数。 what!! 反正我是很不理解,也可能是我理解有偏差,我觉得我想说设置个时间还要去算加减乘除计算我想要的时间距一个时间的ms数,也太麻烦了吧。

如果有大佬知道,希望能指点一二!拜谢!

4.一些吐槽

然后网上搜Timestamp怎么赋初值,得到的全是关于如何获取当前时间的,Date类型的一些应用。而我这里只是想做测试的时候写出一个预期输出的时间戳。但是竟然没有一篇文章正经指出这个怎么给时间戳赋值。(有也给得很模糊,大概就是丢个函数接口出来)!

所以我直接自己去做实验!写下此文! 希望对你有所帮助!

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值