String的时间格式与Date类型互转

今天想把从服务器返回的时间格式的String字符串的转为Date,一下子想不起来。现在记录一下,以后忘记了也方便查找。

①将“yyyy-MM-dd HH:mm:ss”格式的字符串转换为Date类型

package test;

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

/**
 * 将指定格式的字符串转换为Date类型
 *
 * @author chenzhengzhou
 * @version 1.0
 * @date 2018/9/14 15:36
 */
public class DateFormatTest {

    public static void main(String[] args) {

        //要转化的特定格式String字符串
        String date = "2018-9-14 15:16:35";
        System.out.println("转换前的String类型:   " + date);

        //创建DateFormat的对象,在构造器中传入跟要转换的String字符串相同格式的
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = null;
        try {
            //转换的过程中可能会抛出ParseException,必须抛出或者捕获处理
            now = dateFormat.parse(date);
        } catch (ParseException e) {}

        System.out.println("转换后的Date类型:     " + now);
    }
}

 输出结果:

②将Date类型转换为指定格式的String类型字符串

package test;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;

/**
 * 将指定格式的字符串转换为Date类型
 *
 * @author chenzhengzhou
 * @version 1.0
 * @date 2018/9/14 15:36
 */
public class DateFormatTest {

    public static void main(String[] args) {

        //获取目前时间
        Date now = Date.from(Instant.now());
        System.out.println("转换前的Date类型:     " + now);
        //创建DateFormat的对象,在构造器中传入跟要转换格式的String字符串
        DateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
        System.out.println("转换后的String类型:   " + dateFormat.format(now));
    }
}

 输出结果:

String时间格式必须遵守标准:


yyyy:年
MM:月
dd:日
hh:1~12小时制(1-12)
HH:24小时制(0-23)
mm:分
ss:秒
S:毫秒
E:星期几
D:一年中的第几天
F:一月中的第几个星期(会把这个月总共过的天数除以7)
w:一年中的第几个星期
W:一月中的第几星期(会根据实际情况来算)
a:上下午标识
k:和HH差不多,表示一天24小时制(1-24)。
K:和hh差不多,表示一天12小时制(0-11)。
z:表示时区

目前觉得上面的方法比较一般。以后有时间再改吧。

猜你喜欢

转载自blog.csdn.net/chenzz2560/article/details/82700408
今日推荐