java.textSimpleDateFormatクラス(時間から文字列、文字列から時間)

概要概要

SimpleDateFormatクラスは、カスタム形式でフォーマットされたJavaクラスであり、主に次の型変換を実行できます:time-> string(format)、string-> time(parse)

**:フォーマットする前に、文字列に従ってSimpleDateFormatクラスを宣言してください。

文字列の日付

/**
 * 日期转字符串
 */
SimpleDateFormat sim = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str = sim.format(new Date());
System.out.println(str);

SimpleDateFormat sim2 = new SimpleDateFormat("一年中的第D天,一年中的第W个星期,一个月中的第W个星期,一天中的k时 z时区");
String str2 = sim2.format(new Date());
System.out.println(str2);

StringBuilder strb = new StringBuilder();
strb.append("yyyy年MM月dd日 ")
        .append("上下午标志:a ")
        .append("E ")
        .append("一年中的第D天 ")
        .append("一年中的第F个星期 ")
        .append("一年中的第w个星期 ")
        .append("一年中的第W个星期 ")
        .append("z ")
        .append("Z ");
SimpleDateFormat sdf = new SimpleDateFormat(strb.toString());
String dateString = sdf.format(new Date());
System.out.println(dateString);

出力:

2021010213:27:26
一年中的第2天,一年中的第1个星期,一个月中的第1个星期,一天中的13时 CST时区
20210102日 上下午标志:下午 星期六 一年中的第2天 一年中的第1个星期 一年中的第1个星期 一年中的第1个星期 CST +0800 

時間への文字列

/**
 * 字符串转日期
 */
SimpleDateFormat sim4 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String strDate = "2020年1月1日 8:05:21";
Date parse = null;
try {
    
    
    parse = sim4.parse(strDate);
} catch (ParseException e) {
    
    
    e.printStackTrace();
}
System.out.println(parse.toLocaleString());

出力:

2020-1-1 8:05:21

おすすめ

転載: blog.csdn.net/weixin_44613100/article/details/112095359