时间格式化处理

Java时间格式化

java中的时间类基本涉及下面几种:

  1. java.util.Date 具体类(和抽象类相对的)
  2. java.text.DateFormat (抽象类),java.text.SimpleDateFormat (是java.text.DateFormat 类的具体子类)
  3. java.util.Calendar(抽象类),java.util.GregorianCalendar(java.util.Calendar的具体子类)

因为具体类可以被实例化, 但是抽象类不能。所以在使用抽象类时候需要使用其静态方法。比如在创建 DateFormat 对象时不能使用 new 关键字,而应该使用 DateFormat 类中的静态方法 getDateInstance()。具体看DateFormat 类

Date 类

package demo5;

import java.util.Date;

public class demo5_4 {
    public static void main(String[] args) {
        Date d = new Date();
    
        System.out.println(d);   // 输出结果 Fri Jan 03 17:26:16 CST 2020
        System.out.println(d.getTime());  // 1578043672353
    }
}

输出结果:

Fri Jan 03 17:27:52 CST 2020
1578043672353

getTime()方法获取到的是从1970年1月1日开始经历的毫秒数, 但是日常使用的是年月日格式的日期。所以就需要使用下面的类。

SimpleDateFormat 类

SimpleDateFormat是DateFormat 类的子类。SimpleDateFormat类是个具体类, 是可以进行实例化的。 SimpleDateFormat可以指定时间的格式。
SimpleDateFormat 类主要有如下 3 种构造方法。

  • SimpleDateFormat():用默认的格式和默认的语言环境构造 SimpleDateFormat。
  • SimpleDateFormat(String pattern):用指定的格式和默认的语言环境构造 SimpleDateF ormat。
  • SimpleDateFormat(String pattern,Locale locale):用指定的格式和指定的语言环境构造
    SimpleDateF ormat。
class FormatTime {
    public void main() {

        Date d = new Date();
        SimpleDateFormat sf1 = new SimpleDateFormat("yyyy-MM-dd H:m:s"); // 指定格式
        SimpleDateFormat sf2 = new SimpleDateFormat();   // 不指定格式, 默认的格式

        System.out.println(sf1.format(d)); 
        System.out.println(sf2.format(d));
    }
}

输出结果:

2020-01-03 17:10:11
20-1-3 下午5:10

上面是将时间转为文本。 下面使用SimpleDateFormat类将文本转为时间。

package demo5;

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

public class demo5_4 {
    public static void main(String[] args) {
        String time_test = "2020-01-03";
        SimpleDateFormat dateToString = new SimpleDateFormat("yyyy-MM-dd");
        try{
            Date date1 = dateToString.parse(time_test);
            System.out.println(date1);
        }catch (Exception e){
            System.out.println("error");

        }
    }
}

输出结果是:

Fri Jan 03 00:00:00 CST 2020

是将字符串"2020-01-03"通过 SimpleDateFormat类的parse方法转为 Date类。

DateFormat 类

DateFormat 是日期/时间格式化子类的抽象类,它以与语言无关的方式格式化并解析日期或时间。
在创建 DateFormat 对象时不能使用 new 关键字,而应该使用 DateFormat 类中的静态方法 getDateInstance()。
因为DateFormat是抽象类。
示例代码如下:

DateFormat df = DateFormat.getDatelnstance();

未完待续

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值