关于Date

关于Date

1. java.util.Date

java.util.Date类中有一个 fastTime属性,此属性保存时间的long类型值,Date类型在java中是以long类型保存的,与1970.01.01的时间差。

2.获取当前时间

Date now = new Date( ); //获得Date类型当前时间
long now = new Date( ).getTime(); //获得long类型当前时间

jdk中相应构造函数如下,可看出在构造Date时是将系统当前时间的毫秒表示赋值给fastTime属性。

  /**
     * Allocates a <code>Date</code> object and initializes it so that
     * it represents the time at which it was allocated, measured to the
     * nearest millisecond.
     *
     * @see     java.lang.System#currentTimeMillis()
     */
    public Date() {
        this(System.currentTimeMillis());
    }

    /**
     * Allocates a <code>Date</code> object and initializes it to
     * represent the specified number of milliseconds since the
     * standard base time known as "the epoch", namely January 1,
     * 1970, 00:00:00 GMT.
     *
     * @param   date   the milliseconds since January 1, 1970, 00:00:00 GMT.
     * @see     java.lang.System#currentTimeMillis()
     */
    public Date(long date) {
        fastTime = date;
    }

Date类的getTime( )方法则是返回faseTime属性。

   /**
     * Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
     * represented by this <tt>Date</tt> object.
     *
     * @return  the number of milliseconds since January 1, 1970, 00:00:00 GMT
     *          represented by this date.
     */
    public long getTime() {
        return getTimeImpl();
    }

    private final long getTimeImpl() {
        if (cdate != null && !cdate.isNormalized()) {
            normalize();
        }
        return fastTime;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Date数据类型格式化的转换,可以使用Java中的SimpleDateFormat类来实现。SimpleDateFormat类是一个用于格式化和解析日期的类。 下面是一个简单的示例代码,将Date类型的数据转换为指定格式的字符串: ``` import java.text.SimpleDateFormat; import java.util.Date; public class DateTest { public static void main(String[] args) { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String str = sdf.format(date); System.out.println(str); } } ``` 在上述代码中,我们首先创建了一个Date对象,然后创建了一个SimpleDateFormat对象,并指定了要转换的日期格式。最后调用SimpleDateFormat对象的format方法将Date对象转换为字符串。 如果要将字符串转换为Date对象,则可以使用SimpleDateFormat类的parse()方法。下面是一个示例代码: ``` import java.text.SimpleDateFormat; import java.util.Date; public class DateTest { public static void main(String[] args) throws Exception { String str = "2021-05-20 16:30:00"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = sdf.parse(str); System.out.println(date); } } ``` 在上述代码中,我们首先创建了一个字符串对象,表示要转换的日期字符串。然后创建了一个SimpleDateFormat对象,并指定了要转换的日期格式。最后调用SimpleDateFormat对象的parse方法将字符串转换为Date对象。注意,parse方法可能会抛出ParseException异常,所以需要进行异常处理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值