专业的JAVA编程教程与资源

网站首页 > java教程 正文

字符串日期格式化时间格式化日期时间组合格式化情形

temp10 2024-10-24 17:19:27 java教程 12 ℃ 0 评论

1.字符串日期格式化

常用的日期格式化转换符

字符串日期格式化时间格式化日期时间组合格式化情形

%te ,一个月中的某一天(1~31), 如:2

%tb ,指定语言环境的月份简称,如: Feb(英文)、二月(中文)

%tB, 指定语言环境的月份全称 ,如:February(英文)、二月(中文)

%tA ,指定语言环境的星期几全称,如: Monday(英文)、星期一 (中文)

%ta ,指定语言环境的星期几简称, 如:Mon(英文)、星期一(中文)

%tc, 包括全部日期和时间信息,如:星期二 三月 23 13:37:22 CST 2010

%tY ,4 位年份,如 2010

%tj ,一年中的第几天(001~366), 如085

%tm, 月份,如 01

%td, 一个月中的第几天(01~31) ,如02

%ty, 2位年份, 如09

在项目中创建类GetDate, 实现将当前日期信息以4位年份、月份全称、2 位日期形式输出。

import java. util. Date; //导入java. util. Date类

public class GetDate{ //新建类

public static void main(String[] args) { //主方法

Date date = new Date(); //创建Date 对象 date

String year = String. format("%tY", date);

String month = String. format("%tm", date);

String day = String. format("%td", date);

String day1 = String. format("%tj", date);

System. out. println("今年是: " + year + "年"); //输出信息

System. out. println("现在是: " + month+"月");

System. out. println("今天是: " + day + "日");

System. out. println("今天是一年中的第: " + day1 + "天");

运行结果

今年是: 2024年

现在是:01

今天是: 29号

今天是一年中的第029天

2.字符串时间格式化

使用 format()方法可以实现时间的格式化,可以将时间格式化为时、分、秒、毫秒。

时间格式化转换符

%tH, 2位数字的24时制的小时(00~23) ,如:13

%tl ,2位数字的 12时制的小时(01~12) ,05

%tk ,1~2位数字的 24时制的小时(0~23) ,如:5

%tM, 2位数字的分钟(00~59), 如05

%tS,2位数字的秒数(00~60), 如12

%tL, 3 位数字的毫秒数(000~999),如: 666

%tN, 9位数字的微秒数(000000000~999999999),如 062000000

%tp, 指定语言环境下上午或下午标记, 下午 (中文)、pm(英文)

%tz, 相对于 GMT RFC 82 格式的数字时区偏移量, +0800

%tZ, 时区缩写形式的字符串, CST

%ts, 1970-01-01 00:00:00 至现在经过的秒数, 1206426646

%tQ, 1970-01-01 00:00:00 至现在经过的毫秒数, 1206426737453

在项目中创建类 GetTime,实现将当前时间信息以2位小时数、2位分钟数、2位秒数形式输出,并显示上午或下午。

import java. util. Date; //导入java. util. Date类

public class GetTime{

public static void main(String[] args) {

Date date = new Date();

String hour = String.format("%tH", date);

String minute = String.format("%tM", date);

String second = String.format("%tS", date);

System.out.println("现在是:" + hour + "点" + minute + "分" + second + "秒");

String hour2 = String.format("%tI", date);

String pm = String.format("%tp", date);

System.out.println("现在是:" + pm + hour2 + "点" + minute + "分" + second + "秒");

}

}

运行结果:

现在是20点20分32秒

现在是下午08点20分32秒


3.字符串日期时间组合格式化形式

常见的日期和时间组合的格式

%tF,“年-月-日”格式(4位年份) ,如2008-03-25

%tD,“月/日/年”格式(2位年份) ,如03/25/08

%tc ,全部日期和时间信息,如:星期二 三月 25 15:20:00 CST 2008

%tr,“时: 分: 秒 PM(AM)”格式(12时制),如: 03:22:06 下午

%tT,“时: 分: 秒”格式(24时制) ,15:23:50

%tR ,“时: 分”格式(24时制) ,15:25

在项目中创建类DateAndTime,在主方法中实现将当前日期时间的全部信息以指定格式的日期输出。

import java. util. Date; //导入java. util. Date类

public class DateAndTime { //创建类

public static void main(String[] args) { //主方法

Date date = new Date(); //创建Date 对象 date

String date1= String. format("%tF", date);

String time1 = String. format("%tT", date);

//将格式化后的日期时间输出

System. out. println("年-月-日格式: " + date1);

System. out. println("时: 分: 秒格式: " + time1);

}

运行结果:

年-月-日格式: 2024-01-29

时: 分: 秒格式:20:20:32


本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表