21xrx.com
2024-09-17 04:19:30 Tuesday
登录
文章检索 我的文章 写文章
Java时间类型转换成字符串的几种方法
2023-06-16 06:08:40 深夜i     --     --
Java 时间类型 字符串 SimpleDateFormat DateTimeFormatter String

在开发Java程序时,常常需要将时间类型转换成字符串,以便于在界面上显示或者作为参数传递给其他系统。本文将介绍Java中时间类型转换成字符串的几种方法。

1. 使用SimpleDateFormat类

SimpleDateFormat是Java中常用的时间格式化类,它可以将Date类型转换成指定格式的字符串。

举个例子,将当前时间转换成年月日时分秒的格式可以这样写:


import java.text.SimpleDateFormat;

import java.util.Date;

public class Test {

  public static void main(String[] args) {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    String str = sdf.format(new Date());

    System.out.println(str);

  }

}

输出结果如下:


2021-10-27 15:28:21

2. 使用DateTimeFormatter类

DateTimeFormatter是Java8中的新类,用于进行日期时间的格式化和解析。它支持ISO-8601标准格式,也支持自定义格式。

举个例子,将当前时间转换成年月日时分秒的格式可以这样写:


import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;

public class Test {

  public static void main(String[] args) {

    LocalDateTime now = LocalDateTime.now();

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    String str = formatter.format(now);

    System.out.println(str);

  }

}

输出结果如下:


2021-10-27 15:28:21

3. 使用String.format方法

String类的format方法可以将字符串按照指定格式进行格式化,其中可以使用“%t”占位符来表示时间类型。

举个例子,将当前时间转换成年月日时分秒的格式可以这样写:


import java.util.Calendar;

public class Test {

  public static void main(String[] args) {

    Calendar cal = Calendar.getInstance();

    String str = String.format("%tF %tT", cal, cal);

    System.out.println(str);

  }

}

输出结果如下:


2021-10-27 15:28:21

.format。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复