Java date format 时间格式化

合集下载

日期时间类:Date类日期时间格式化(DateFormat类)Calendar类

日期时间类:Date类日期时间格式化(DateFormat类)Calendar类

⽇期时间类:Date类⽇期时间格式化(DateFormat类)Calendar类⽇期时间类Date类注:以下介绍的Date都在java.util包下,除此之外,java.sql包下也有此类,不要混淆构造⽅法1. Date():分配Date对象并初始化此对象,以表⽰分配他的时间(精确到毫秒)2. Date(long date):分配Date对象并初始化此对象,以表⽰⾃标准基准时间(即1970年1⽉1⽇00:00:00GMT)起指定毫秒数Date后的时间使⽤第⼆种构造⽅法要先创建⼀个Date对象//在此之前要导⼊Date类import java.util.Date;long t=System.currentTimeMillis();Date date = new Date(t);注:使⽤Date对象⽤的是longDate类的常⽤⽅法和说明⽅法说明after(Date when)测试当前⽇期是否在指定⽇期之后before(Date when)测试当前⽇期是否在指定⽇期之前getTime()获得⾃1970年1⽉1⽇00:00:00GMT起到现在所经过的毫秒数setTime(long time)设置当前Date对象所表⽰的⽇期时间值,该值⽤以表⽰1970年1⽉1⽇00:00:00GMT以后time毫秒的时间点获取当前⽇期和时间import java.util.Date;public static void main(String[] args) {Date date = new Date();long value= date.getTime();//获得毫秒数System.out.println("⽇期:"+date);System.out.println("到现在所经历的毫秒数是:"+value);}/*⽇期:Sat Sep 04 18:44:19 CST 2021到现在所经历的毫秒数是:1630752259575*/⽇期时间格式化(DateFormat类)格式化风格有以下4种(以2021年9⽉2⽇举例)SHORT:完全为数字MEDIUM:较长LONG:更长FULL:完全指定要格式化⽇期,⾸先要创建DateFormat对象,因为他是抽象类,所以可以⽤getDateInstance()进⾏创建DateFormat d=DateFormat.getDateInstance();此类常⽤⽅法和说明⽅法说明format()将⼀个Date对象实例格式化为⽇期/时间字符串⽅法说明getCalendar()获取于此⽇期/时间格式器关联的⽇历getDateInstance()获取⽇期格式器,该格式器具有默认语⾔环境的默认格式化风格getDateTimeInstance()获取⽇期/时间格式器,该格式器具有默认语⾔环境的默认格式化风格getInstance()获取为⽇期和时间使⽤SHORT风格的默认⽇期/时间格式器getTimeInstance()获取时间格式器,该格式器具有默认语⾔环境的默认格式化风格parse(String source)将字符串解析成⼀个⽇期,并返回这个⽇期的Date对象实例如下import java.text.DateFormat;import java.util.Date;public static void main(String[] args) {//将当前⽇期按照默认模式输出DateFormat d1=DateFormat.getInstance();System.out.println(d1.format(new Date()));//21-9-6 下午4:40//输出长类型格式的当前时间DateFormat d2=DateFormat.getTimeInstance(DateFormat.LONG);System.out.println(d2.format(new Date()));//下午04时40分48秒//输出长类型格式的当前⽇期DateFormat d3=DateFormat.getDateInstance(DateFormat.LONG);System.out.println(d3.format(new Date()));//2021年9⽉6⽇//输出长类型格式的当前时间和⽇期DateFormat d4=DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);System.out.println(d4.format(new Date()));//2021年9⽉6⽇下午04时40分48秒}因为DateFormat是⼀个抽象类,所以,除了使⽤getXXXInstance()⽅法创建对象,还可以⽤其⼦类,例如SimpleDateFormat类,此类提供了19个格式化字符,可以让开发者随意编写⽇期格式SimpleDateFormat类提供的格式化字符字母⽇期或时间元素类型⽰例G Era标识志符Text ADy年Year2021;21M年中的⽉份Month July;Jul;07w年中的周数Number22W⽉份中的周数Number3D年中的天数Number56d⽉份中的天数Number15F⽉份中的星期Number3E星期中的天数Text Monday;Mona Am/pm标记Text PMH⼀天中的⼩时数(0~23)Number11h am/pm中的⼩时数(1~12)Number2k⼀天中的⼩时数(1~24)Number22K am/pm中的⼩时数(0~11)Number10m⼩时中的分钟数Number35s分钟中的秒数Number50S毫秒数Number555z时区General time zone Pacific Standard Time;PST;GMT-08:00Z时区RFC 822 time zone-800⼀般表中字母的数量会影响数字的格式,例如yyyy表⽰4位年份:2021,yy表⽰2位年份:21,y表⽰4位年份,如果超过4个y,则在左侧补0,yyyyyy表⽰002021常⽤时间格式⽇期时间对应的格式2021/9/6yyyy/MM/dd2021.9.6yyyy.MM.dd⽇期时间对应的格式2021-09-06 17:42:50yyyy-MM-dd HH.mm.ss2021年9⽉6⽇ 17时46分50秒yyyy年MM⽉dd⽇ HH时mm分ss秒下午5时ah时今年已经过去了200天今年已经过去了D天⽰例如下import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;public static void main(String[] args) {DateFormat d = new SimpleDateFormat("yyyy年MM⽉dd⽇ EEEE HH时mm分ss秒");System.out.println("现在是:");System.out.println(d.format(new Date()));//2021年09⽉06⽇星期⼀ 17时51分17秒}Calendar类Date在设计时并没有考虑国际化,所以之中的⽅法并不能满⾜当下需求,所以就有了Calendar类的出现,也是⼀个抽象类,该类提供了⼀些字段和⽅法,这些字段和⽅法被定义为protected。

Java中日期格式化YYYY-DD的坑正确写法:yyyy-MM-ddHH:mm

Java中日期格式化YYYY-DD的坑正确写法:yyyy-MM-ddHH:mm

Java中⽇期格式化YYYY-DD的坑正确写法:yyyy-MM-ddHH:mm摘⾃:2020-01-05 19:27 阅读(115) 评论(0)写这篇博⽂是记录下跨年的bug。

去年隔壁组的⼩伙伴就是计算两个⽇期之间间隔的天数,因为跨年的原因计算有误。

当时测试组的⼩姐姐也没有模拟出来这种场景,导致上⽣产环境直接影响线上的数据。

今天逛技术论论坛正好遇到Java⽇期的操作bug。

1 yyyy 和 YYYY别看字,看代码@Testpublic void testWeekBasedYear() {Calendar calendar = Calendar.getInstance();// 2019-12-31calendar.set(2019, Calendar.DECEMBER, 31);Date strDate1 = calendar.getTime();// 2020-01-01calendar.set(2020, Calendar.JANUARY, 1);Date strDate2 = calendar.getTime();// ⼤写 YYYYSimpleDateFormat formatYYYY = new SimpleDateFormat("YYYY/MM/dd");System.out.println("2019-12-31 转 YYYY/MM/dd 格式: " + formatYYYY.format(strDate1));System.out.println("2020-01-01 转 YYYY/MM/dd 格式: " + formatYYYY.format(strDate2));// ⼩写 YYYYSimpleDateFormat formatyyyy = new SimpleDateFormat("yyyy/MM/dd");System.out.println("2019-12-31 转 yyyy/MM/dd 格式: " + formatyyyy.format(strDate1));System.out.println("2020-01-01 转 yyyy/MM/dd 格式: " + formatyyyy.format(strDate2));}输出结果2019-12-31 转 YYYY/MM/dd 格式: 2020/12/312020-01-01 转 YYYY/MM/dd 格式: 2020/01/012019-12-31 转 yyyy/MM/dd 格式: 2019/12/312020-01-01 转 yyyy/MM/dd 格式: 2020/01/01细⼼的同学应该发现了2019-12-31⽤YYYY/MM/dd此刻变成了2020/12/31??为何呢?YYYY这么⼤的能耐,能跑到2020年代去?我2019年底买的东西,你如果⽤YYYY来格式化出库⽇期,我是不是得到2020年底才能收到货?此bug问题挺⼤的呀!YYYY 到底是何⽅妖怪?Java's DateTimeFormatter pattern "YYYY" gives you the week-based-year, (by default, ISO-8601 standard) the year of theThursday of that week.例⼦:下⾯就是⽤YYYY格式化代码12/29/2019 将会格式化到2019年这⼀周还属于2019年12/30/2019 将会格式化到2020年这⼀周已经属于2029年看字说话YYYY,week-based year 是 ISO 8601 规定的。

mybatis dateformat用法 -回复

mybatis dateformat用法 -回复

mybatis dateformat用法-回复MyBatis是一个流行的Java持久化框架,它提供了灵活的ORM(对象关系映射)功能,使开发人员可以轻松地将Java对象映射到数据库表中。

作为一个功能强大的框架,MyBatis提供了很多有用的特性,其中之一就是日期格式化功能。

本文将一步一步地回答关于MyBatis日期格式化功能的问题,以帮助读者了解其用法。

首先,让我们了解一下为什么需要日期格式化功能。

当我们在数据库中存储日期数据时,通常会使用不同的日期格式,例如yyyy-MM-dd或yyyy/MM/dd。

但是,Java中的日期对象通常具有不同的格式,例如java.util.Date或java.time.LocalDate。

因此,当我们将Java对象中的日期属性映射到数据库表中时,我们需要进行日期格式化。

在MyBatis中,日期格式化功能通过`@DateTimeFormat`注解来实现。

我们可以将该注解应用在日期类型的属性上,以指定日期的格式。

以下是使用`@DateTimeFormat`注解的示例代码:javapublic class User {private Long id;@DateTimeFormat(pattern = "yyyy-MM-dd")private Date birthDate;getters and setters}在上述示例中,`birthDate`属性被注解`@DateTimeFormat(pattern = "yyyy-MM-dd")`修饰。

该注解指定了日期的格式为"yyyy-MM-dd",这与大多数数据库中广泛使用的日期格式相匹配。

当我们在MyBatis的映射文件中使用这个日期属性时,MyBatis会自动将其格式化为指定的格式。

以下是一个示例映射文件的代码片段:xml<resultMap id="userResultMap" type="User"><id property="id" column="user_id"/><result property="birthDate" column="birth_date"/></resultMap>在上述代码片段中,`<result>`标签用于映射数据库表中的列到User对象中的属性。

datetimeformat注解原理

datetimeformat注解原理

datetimeformat注解原理一、概述datetimeformat注解是一种用于处理日期和时间的注解,它可以帮助我们在Java编程中更方便地处理日期和时间相关的数据。

该注解在Java的Spring框架中广泛应用,用于格式化日期和时间的显示方式。

二、注解原理1. 定义和使用:datetimeformat注解通常用于注解一个字段,表示该字段需要被格式化成特定的日期和时间格式。

注解通常需要指定一个或多个格式选项,如yyyy-MM-dd、HH:mm:ss等。

2. 格式化规则:datetimeformat注解使用的是Java内置的SimpleDateFormat类来实现日期和时间的格式化。

SimpleDateFormat类提供了一组方法,可以根据指定的格式规则将日期和时间转换为字符串,或将字符串转换为日期和时间。

3. 默认格式:如果没有为datetimeformat注解指定格式选项,则默认使用ISO 8601格式。

该格式可以将日期和时间表示为字符串,如"yyyy-MM-dd'T'HH:mm:ss.SSSZ"。

4. 自定义格式:如果需要使用自定义的日期和时间格式,可以在datetimeformat注解中指定。

格式选项可以是基本的日期和时间格式,也可以是自定义的日期和时间格式。

三、常见用法在Spring框架中,datetimeformat注解通常用于注解数据库字段或表单字段,以指定显示日期和时间的格式。

例如,以下是一个使用datetimeformat注解的示例:@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")private Date dateField;这个注解告诉编译器,dateField字段的值应该被格式化为"yyyy-MM-dd HH:mm:ss"的字符串形式。

四、注意事项在使用datetimeformat注解时,需要注意以下几点:1. 确保在使用datetimeformat注解时,指定的格式选项是有效的日期和时间格式。

Java使用DateTimeFormatter格式化输入的日期时间

Java使用DateTimeFormatter格式化输入的日期时间

Java使⽤DateTimeFormatter格式化输⼊的⽇期时间要求:⽤DateTimeFormatter实现: ⽤扫描器获取输⼊的时间(年⽉⽇时分),这个时间的格式是常⽤的格式,然后格式化这个时间,把格式化的时间输出到控制台,可以在控制台重复输⼊时间.格式化的时间参考企业微信聊天记录的展⽰时间分析:1.时间的常⽤格式为:xxxx-xx-xx xx:xxxxxx/xx/xx xx:xxxxxx.xx.xx xx:xx等格式2.微信显式时间格式为:今天显式: 00:01 - 23:59 ;昨天显式: 昨天 01:01 ;前天显式: 周⼏ 02:02往前推⼀周都显式: 周⼏ 02:02 ;时间再往前推只显⽰: ⼏⽉⼏⽇ 02:02不同年则显式: ⼏年⼏⽉⼏⽇ 02:02也可考虑写⼀个明天显式: 明天 02:02其余时间显式: ⼏⽉⼏⽇ 02:023.考虑特殊情况下的⽇期:⽐如当前天是1号则上个⽉的最后⼀天是昨天往前推⼀周则显式:星期⼏ 02:02如果当前天不⼤于7号则向前推⼀周到了上个⽉也要考虑将其转换为星期4.先输⼊⼀个时间,再对这个时间使⽤DateTimeFormatter进⾏格式化⽐如:输⼊: 2020-1-11 12:22则格式化结果为:下午 12:22代码实现程序开始:package hrkj.chapter7.dateTimeFormatter.Test1;/*** 程序开始⼊⼝ <br>* 2020年1⽉9⽇下午7:10:04** @author wcf* @version 1.0*/public class Test {/*** 程序⼊⼝** @param args ⼊⼝参数*/public static void main(String[] args) {// 程序开始运⾏DateTimeFormatterTest.inoutDateTime();}}⽇期时间等需要⽤到的正则表达式:package hrkj.chapter7.dateTimeFormatter.Test1;/*** ⽇期时间的正则表达式 <br>* 2020年1⽉9⽇下午7:25:11** @author wcf* @version 1.0*/public enum Regex {/*** 匹配闰年*/LEEP_YEAR("((\\d{2}(0[48]|[2468][048]|[13579][26]))|((0[48]|[2468][048]|[13579][26])00))[-\\/\\.]0?2[-\\/\\.]29"),/*** 匹配平年*/COMMON_YEAR("(\\d{3}[1-9]|\\d{2}[1-9]\\d|\\d[1-9]\\d{2}|[1-9]\\d{3})[-\\/\\.]((0?[13578]|1[02])[-\\/\\.](0?[1-9]|[12]\\d|3[01])|((0?[469]|11)[-\\/\\.](0?[1-9]|[12]\\d|30))|(0?2[-\\/\\.](0?[1-9]|1\\d|2[0-8])))"), /*** 匹配时间*/TIME(" ([01]?\\d|2[0-3]):[0-5]?\\d"),/*** 退出程序*/EXIT("exit|退出");/*** 正则*/private final String str;/*** 有参构造器** @param string 正则*/private Regex(String string) {this.str = string;}/*** 获取正则** @return 正则*/public String getStr() {return str;}}提⽰信息:package hrkj.chapter7.dateTimeFormatter.Test1;/*** 提⽰信息 <br>* 2020年1⽉9⽇下午7:25:53** @author wcf* @version 1.0*/public enum Hint {/*** 请输⼊⽇期时间*/INPUT_DATE_TIME("请输⼊⽇期时间:"),/*** ⽇期时间格式*/DATETIMEFORMAT("常⽤格式:xxxx-xx-xx xx:xx\n\t xxxx/xx/xx xx:xx\n\t xxxx.xx.xx xx:xx"),/*** ⽇期错误*/INVOKE_DATE("⽇期错误"),/*** 时间错误*/INVOKE_TIME("时间错误"),/*** ⽇期时间错误*/INVOKE_DATE_TIME("⽇期时间错误!"),/*** 继续或退出*/CONTINUE_OR_QUIT("exit:程序退出\n请输⼊:"),/*** 程序结束*/END_OF_PROGRAM("退出成功,程序结束!");/*** 提⽰*/private final String str;/*** 有参构造器** @param str 提⽰*/private Hint(String str) {this.str = str;}/*** 获取提⽰*/public void println() {System.out.println(str);}}⽇期时间格式化的模板字符串:package hrkj.chapter7.dateTimeFormatter.Test1;/*** ⽇期时间格式化的模板字符串 <br>* 2019年3⽉1⽇下午7:17:19** @author wcf* @version 1.0*/public enum Pattern {/*** 上下午时分*/TIME("a HH:mm"),/*** 昨天时分*/YESTERDAY("昨天 HH:mm"),/*** 明天时分*/TOMORROW("明天 HH:mm"),/*** 星期时分*/WEEK_TIME("E HH:mm"),/*** ⽉⽇时分*/MONTH_DAY_TIME("M⽉d⽇ HH:mm"),/*** 年⽉⽇时分*/YEAR_MONTH_DAY_TIME("y年M⽉d⽇ HH:mm");/*** 显式模式*/private final String str;/*** 有参数构造器** @param str 模式*/private Pattern(String str) {this.str = str;}/*** 获取显式模式** @return 显式模式*/public String getStr() {return str;}}输⼊⽇期时间进⾏处理:package hrkj.chapter7.dateTimeFormatter.Test1;import java.util.Scanner;/*** 输⼊⽇期时间进⾏处理 <br>* 2020年1⽉9⽇下午7:09:31** @author wcf* @version 1.0*/public class DateTimeFormatterTest {/*** 闰年正则*/private final static String LEEP_YEAR = Regex.LEEP_YEAR.getStr(); /*** 平年正则*/private final static String COMMON_YEAR = MON_YEAR.getStr();/*** 时间正则*/private final static String TIME = Regex.TIME.getStr();/*** 退出正则*/private final static String EXIT = Regex.EXIT.getStr();/*** 静态初始化块*/static {// 输⼊提⽰Hint.INPUT_DATE_TIME.println();// ⽇期时间格式Hint.DATETIMEFORMAT.println();// 退出指令Hint.CONTINUE_OR_QUIT.println();}/*** 私有构造器*/private DateTimeFormatterTest() {// 私有构造器// ⽆法创建本类实例}/*** 输⼊⽇期时间*/public static void inoutDateTime() {// 扫描器Scanner scanner = new Scanner(System.in);// 扫描控制台输⼊while (scanner.hasNextLine()) {// 接收控制台输⼊,并去除输⼊前后的空格String str = scanner.nextLine().trim();// 对输⼊的字符进⾏判断if (str.matches(EXIT)) {// 程序退出Hint.END_OF_PROGRAM.println();// 关闭扫描器scanner.close();// 退出虚拟机System.exit(0);// 判断平闰年} else if (str.matches(LEEP_YEAR + TIME) || str.matches(COMMON_YEAR + TIME)) {// 对输⼊的⽇期时间字符串进⾏格式化DateTimeFormatterTools.format(str);// 格式化后提⽰Hint.CONTINUE_OR_QUIT.println();} else {// 输⼊的⽇期时间不正确Hint.INVOKE_DATE_TIME.println();// 输⼊提⽰Hint.INPUT_DATE_TIME.println();continue;}}}}对输⼊的⽇期时间进⾏处理:package hrkj.chapter7.dateTimeFormatter.Test1;import java.time.LocalDateTime;import java.time.MonthDay;import java.time.Year;import java.time.format.DateTimeFormatter;import java.util.Arrays;/*** 对输⼊的⽇期时间进⾏处理 <br>* 2020年1⽉9⽇下午8:08:45** @author wcf* @version 1.0*/public class DateTimeFormatterTools {/*** 年⽉⽇时分*/private static final String YEAR_MONTH_DAY_TIME = Pattern.YEAR_MONTH_DAY_TIME.getStr(); /*** ⽉⽇时分*/private static final String MONTH_DAY_TIME = Pattern.MONTH_DAY_TIME.getStr();/*** 星期时分*/private static final String WEEK_TIME = Pattern.WEEK_TIME.getStr();/*** 上下午时分*/private static final String TIME = Pattern.TIME.getStr();/*** 昨天时分*/private static final String YESTERDAY = Pattern.YESTERDAY.getStr();/*** 明天时分*/private static final String TOMORROW = Pattern.TOMORROW.getStr();/*** 当前年*/private static int currentYear = Year.now().getValue();/*** 当前⽉*/private static int currentMonth = MonthDay.now().getMonthValue();/*** 当前⽇*/private static int currentDay = MonthDay.now().getDayOfMonth();/*** ⼤⽉*/private static int[] bigMonth = { 1, 3, 5, 7, 8, 10, 12 };/*** ⼩⽉*/private static int[] smallMonth = { 4, 6, 9, 11 };/*** 私有构造器*/private DateTimeFormatterTools() {// 私有构造器,⽆法实例化}/*** 处理输⼊的⽇期时间** @param str 输⼊的⽇期时间*/public static void format(String str) {// 将⽇期和时间⽤空格进⾏分割String[] datetime = str.split(" ");// 分割成的⽇期String date = datetime[0];// 分割成的时间String time = datetime[1];// ⽇期分割⽅式String splitter = "";// ⽇期可以⽤- . / 进⾏分割// 如果包含了-./这三种中的⼀种,则⽤这些进⾏分割if (date.contains(".")) {splitter = "\\.";} else if (date.contains("-")) {splitter = "-";} else if (date.contains("/")) {splitter = "/";}// 使⽤⽇期的分割⽅式对⽇期进⾏分割String[] dateString = date.split(splitter);// 使⽤:对时间进⾏分割,时间只能⽤:进⾏分割String[] timeString = time.split(":");// 时间分割后的数组长度不是2则错误,因为输⼊的的时间只有时和分if (timeString.length != 2) {// 时间错误Hint.INVOKE_TIME.println();return;}// ⽇期分割后的数组长度不是3则错误,因为输⼊的⽇期要有年,⽉和⽇if (dateString.length != 3) {// ⽇期错误Hint.INVOKE_DATE.println();return;}// 输⼊的年int year = Integer.valueOf(dateString[0]);// 输⼊的⽉int month = Integer.valueOf(dateString[1]);// 输⼊的⽇int day = Integer.valueOf(dateString[2]);// 输⼊的时int hour = Integer.valueOf(timeString[0]);// 输⼊的分int minute = Integer.valueOf(timeString[1]);// 对拆解判断过的字符串进⾏重新组合String str1 = year + splitter + month + splitter + day + " " + hour + ":" + minute;// 对组合后的字符串进⾏解析DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("y" + splitter + "M" + splitter + "d" + " H:m"); // 将字符串解析成⽇期时间对象LocalDateTime parse = LocalDateTime.parse(str1, ofPattern);// 同⼀年if (year == currentYear) {// 同⼀⽉if (month == currentMonth) {// 同⼀天if (day == currentDay) {// 今天printDateTime(TIME, parse);} else if (day - currentDay == 1) {// 明天printDateTime(TOMORROW, parse);} else if (day - currentDay == -1) {// 昨天printDateTime(YESTERDAY, parse);} else if (day - currentDay >= -7 && day - currentDay <= -2) {// 向前⼀周以星期来表⽰printDateTime(WEEK_TIME, parse);} else {// 不同天printDateTime(MONTH_DAY_TIME, parse);}// 下个⽉} else if (month - currentMonth == 1) {// 如果输⼊的⽇是1,则判断当前⽉和天if (day == 1) {// 判断是⼤⽉⼩⽉还是⼆⽉,如果当前天数是⽉份最后⼀天,则输出明天if (Arrays.binarySearch(bigMonth, currentMonth) >= 0 && currentDay == 31) {// 明天printDateTime(TOMORROW, parse);return;} else if (Arrays.binarySearch(smallMonth, currentMonth) >= 0 && currentDay == 30) { // 明天printDateTime(TOMORROW, parse);return;} else if (currentMonth == 2) {// 判断输⼊的是闰年还是平年if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {if (currentDay == 29) {// 明天printDateTime(TOMORROW, parse);return;}} else {if (currentDay == 28) {// 明天printDateTime(TOMORROW, parse);return;}}} else {// 使⽤⽉⽇进⾏输出printDateTime(MONTH_DAY_TIME, parse);}} else {// 输⼊的⽇不是1,这输出⽉⽇时分printDateTime(MONTH_DAY_TIME, parse);}// 上⼀⽉} else if (month - currentMonth == -1) {// 如果当前⽇是1,则判断输⼊⽇是否是上⽉最后⼀天if (currentDay == 1) {// 判断是⼤⽉⼩⽉还是⼆⽉,输⼊的天数是不是⽉份的最后⼀天,是则是昨天if (Arrays.binarySearch(bigMonth, month) >= 0 && day == 31) {// 昨天printDateTime(YESTERDAY, parse);return;} else if (Arrays.binarySearch(smallMonth, month) >= 0 && day == 30) {// 昨天printDateTime(YESTERDAY, parse);return;} else if (month == 2) {// 判断是闰年还是平年if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {if (day == 29) {// 昨天printDateTime(YESTERDAY, parse);return;}} else {if (day == 28) {// 昨天printDateTime(YESTERDAY, parse);return;}}}}// 如果当前⽇不⼩于7,则输⼊⽉⽇时分,⼩于7则从当前天往前⼀周转换为星期if (currentDay >= 7) {// 输出⽉⽇时分printDateTime(MONTH_DAY_TIME, parse);// 如果当前天⼩于7,则当前天向前⼀周转换为星期} else if (Arrays.binarySearch(bigMonth, month) >= 0 && 31 - day + currentDay < 7) {// 年⽉⽇转换为星期printDateTime(WEEK_TIME, parse);} else if (Arrays.binarySearch(smallMonth, month) >= 0 && 30 - day + currentDay < 7) { // 年⽉⽇转换为星期printDateTime(WEEK_TIME, parse);} else if (month == 2) {// 判断是闰年还是平年if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {if (29 - day + currentDay < 7) {// 年⽉⽇转换为星期printDateTime(WEEK_TIME, parse);} else {// 如果向前超出了⼀周输出⽉⽇时分printDateTime(MONTH_DAY_TIME, parse);}} else {if (28 - day + currentDay < 7) {// 年⽉⽇转换为星期printDateTime(WEEK_TIME, parse);} else {// 如果向前超出了⼀周输出⽉⽇时分printDateTime(MONTH_DAY_TIME, parse);}}} else {// 当前天向前超出了⼀周输出⽉⽇时分printDateTime(MONTH_DAY_TIME, parse);}} else {// 不同⽉,输出⽉⽇时分printDateTime(MONTH_DAY_TIME, parse);}} else {// 不同年,输出年⽉⽇时分printDateTime(YEAR_MONTH_DAY_TIME, parse);}}/*** 格式化结果** @param pattern 模式字符串* @param datetime 时间*/private static void printDateTime(String pattern, LocalDateTime datetime) {// 通过模式字符串对时间进⾏格式化DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern(pattern);// 打印格式化后的时间System.out.println("格式化结果:\n\t" + ofPattern.format(datetime));}}代码测试结果:请输⼊⽇期时间:常⽤格式:xxxx-xx-xx xx:xxxxxx/xx/xx xx:xxxxxx.xx.xx xx:xxexit:程序退出请输⼊:2020-1-11 12:22格式化结果:下午 12:22exit:程序退出请输⼊:2020-1-11 2:22格式化结果:上午 02:22exit:程序退出请输⼊:2020-1-10 1:22格式化结果:昨天 01:22exit:程序退出请输⼊:2020-1-7 12:22格式化结果:周⼆ 12:22exit:程序退出请输⼊:2020-1-12 12:22格式化结果:明天 12:22exit:程序退出请输⼊:2020-1-13 12:22格式化结果:1⽉13⽇ 12:22exit:程序退出请输⼊:2020-2-22 12:22格式化结果:2⽉22⽇ 12:22exit:程序退出请输⼊:2019-12-31 12:22格式化结果:2019年12⽉31⽇ 12:22exit:程序退出请输⼊:更多情况测试,或者代码简化,请⾃⾏探索测试以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

javasimpledateformat类方法

javasimpledateformat类方法

javasimpledateformat类方法Java中的SimpleDateFormat类是一种非常重要的日期格式化工具。

它允许您将日期对象转换为特定格式的字符串,并将字符串解析为日期对象。

SimpleDateFormat类是Java标准库的一部分,因此无需安装任何其他软件即可使用。

SimpleDateFormat类的一些重要方法包括:1. format(Date date):将指定的日期对象格式化为字符串。

例如,以下代码将日期对象格式化为指定格式的字符串:```SimpleDateFormat sdf = new SimpleDateFormat('yyyy-MM-dd'); Date date = new Date();String dateString = sdf.format(date);System.out.println(dateString); // 输出: 2022-01-01```2. parse(String source):将指定的字符串解析为日期对象。

例如,以下代码将字符串解析为日期对象:```SimpleDateFormat sdf = new SimpleDateFormat('yyyy-MM-dd'); String dateString = '2022-01-01';Date date = sdf.parse(dateString);System.out.println(date); // 输出: Sat Jan 01 00:00:00 CST 2022```3. setLenient(boolean lenient):设置是否宽容解析日期。

如果启用宽容解析,则SimpleDateFormat类将尝试解析错误的日期值并将其更正为有效的日期值。

如果禁用宽容解析,则SimpleDateFormat类将抛出ParseException异常。

JAVA格式化日期、时间的方法

JAVA格式化日期、时间的方法

JAVA格式化⽇期、时间的⽅法使⽤ DateFormat 格式化⽇期、时间DateFormat 也是⼀个抽象类,它也提供了如下⼏个类⽅法⽤于获取 DateFormat 对象。

getDateInstance():返回⼀个⽇期格式器,它格式化后的字符串只有⽇期,没有时间。

该⽅法可以传⼊多个参数,⽤于指定⽇期样式和 Locale 等参数;如果不指定这些参数,则使⽤默认参数。

getTimeInstance():返回⼀个时间格式器,它格式化后的字符串只有时间,没有⽇期。

该⽅法可以传⼊多个参数,⽤于指定时间样式和 Locale 等参数;如果不指定这些参数,则使⽤默认参数。

getDateTimeInstance():返回⼀个⽇期、时间格式器,它格式化后的字符串既有⽇期,也有时间。

该⽅法可以传⼊多个参数,⽤于指定⽇期样式、时间样式和 Locale 等参数;如果不指定这些参数,则使⽤默认参数。

上⾯三个⽅法可以指定⽇期样式、时间样式参数,它们是的4个静态常量:FULL、LONG、MEDIUM 和 SHORT,通过这4个样式参数可以控制⽣成的格式化字符串。

看如下例⼦程序。

import java.util.*;import java.text.*;import static java.text.DateFormat.*;public class DateFormatTest {public static void main(String[] args) throws ParseException {// 需要被格式化的时间Date dt = new Date();// 创建两个Locale,分别代表中国、美国Locale[] locales = { Locale.CHINA, };DateFormat[] df = new DateFormat[16];// 为上⾯两个Locale创建16个DateFormat对象for (int i = 0; i < locales.length; i++) {df[i * 8] = DateFormat.getDateInstance(SHORT, locales[i]);df[i * 8 + 1] = DateFormat.getDateInstance(MEDIUM, locales[i]);df[i * 8 + 2] = DateFormat.getDateInstance(LONG, locales[i]);df[i * 8 + 3] = DateFormat.getDateInstance(FULL, locales[i]);df[i * 8 + 4] = DateFormat.getTimeInstance(SHORT, locales[i]);df[i * 8 + 5] = DateFormat.getTimeInstance(MEDIUM, locales[i]);df[i * 8 + 6] = DateFormat.getTimeInstance(LONG, locales[i]);df[i * 8 + 7] = DateFormat.getTimeInstance(FULL, locales[i]);}for (int i = 0; i < locales.length; i++) {String tip = i == 0 ? "----中国⽇期格式----" : "----美国⽇期格式----";System.out.println(tip);System.out.println("SHORT格式的⽇期格式:" + df[i * 8].format(dt));System.out.println("MEDIUM格式的⽇期格式:" + df[i * 8 + 1].format(dt));System.out.println("LONG格式的⽇期格式:" + df[i * 8 + 2].format(dt));System.out.println("FULL格式的⽇期格式:" + df[i * 8 + 3].format(dt));System.out.println("SHORT格式的时间格式:" + df[i * 8 + 4].format(dt));System.out.println("MEDIUM格式的时间格式:" + df[i * 8 + 5].format(dt));System.out.println("LONG格式的时间格式:" + df[i * 8 + 6].format(dt));System.out.println("FULL格式的时间格式:" + df[i * 8 + 7].format(dt));}}}上⾯程序共创建了16个 DateFormat 对象,分别为中国、美国两个 Locale 各创建8个 DateFormat 对象,分别是 SHORT、MEDIUM、LONG、FULL 四种样式的⽇期格式器、时间格式器。

java美式时间格式,日期操作类(DateFormat与SimpleDateFormat)。。。

java美式时间格式,日期操作类(DateFormat与SimpleDateFormat)。。。

java美式时间格式,⽇期操作类(DateFormat与SimpleDateFormat)。

1.DateFormat类此类是⼀个⽇期的格式化类,专门格式化⽇期的操作,因为java.util.Date类本⾝就已经包含了完整的⽇期,所以只需要将些⽇期按照⼀些好的格式格式化⼀下显⽰就好了.观察DateFormat类的定义:此类是定义在java.test包中的。

public abstract class DateFormat extends Format但是定义上可以发现,此类是⼀个抽象类,按照以住的思路,直接使⽤其⼦类实例化即可,但是DateFormat 类本⾝的内部提供了可以直接为其实例化的操作。

得到⽇期的DateFormat对象:public static final DateFormat getDateInstance()得到⽇期时间的DateFormat对象:public static final DateFormat getDateTimeInstance()直接使⽤DateFormat类完成Date类的转换功能:public final String format(Date date)美式⽇期格式12345678910111213import java.text.DateFormat ;import java.util.Date ;public class DateDemo03{public static void main(String args[]){DateFormat df1 =null ;// 声明⼀个DateFormatDateFormat df2 =null ;// 声明⼀个DateFormatdf1 = DateFormat.getDateInstance() ;// 得到⽇期的DateFormat对象df2 = DateFormat.getDateTimeInstance() ;// 得到⽇期时间的DateFormat对象System.out.println("DATE:" + df1.format(new Date())) ;// 按照⽇期格式化System.out.println("DATETIME:" + df2.format(new Date())) ;// 按照⽇期时间格式化}};中式⽇期格式(通过Locale对象指定要显⽰的区域,指定的区域是中国)importjava.text.DateFormat ;importjava.util.Date ;importjava.util.Locale ;publicclassDateDemo04{publicstaticvoidmain(String args[]){DateFormat df1 = null;// 声明⼀个DateFormatDateFormat df2 = null;// 声明⼀个DateFormatdf1 = DateFormat.getDateInstance(DateFormat.YEAR_FIELD,newLocale("zh","CN")) ;// 得到⽇期的DateFormat对象df2 = DateFormat.getDateTimeInstance(DateFormat.YEAR_FIELD,DateFormat.ERA_FIELD,newLocale("zh","CN")) ;// 得到⽇期时间的DateFormat对象System.out.println("DATE:"+ df1.format(newDate())) ;// 按照⽇期格式化System.out.println("DATETIME:"+ df2.format(newDate())) ;// 按照⽇期时间格式化}}; 2.SimpleDateFormat类此类的功能是完成⽇期的显⽰格式化的,例如,在开发中,可以会将⼀种⽇期格式变为另外⼀种⽇期格式,如下所⽰:原始⽇期:2008-10-19 10:11:30.345转换捕⽇期:2008 年 10 ⽉ 19 ⽇ 10 点 11 分 30 秒 345 毫秒但是以上的两个⽇期中⽇期的数字是完全⼀样的,唯⼀不同的是⽇期的显⽰格式不同,所以要想实现这样的转换功能就必须依靠SimpleDateFormat类。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Java date format 时间格式化
java 2010-04-29 01:10:10 阅读880 评论0 字号:大中小
import java.util.Date;
import java.text.DateFormat;
/**
* 格式化时间类
* DateFormat.FULL = 0
* DateFormat.DEFAULT = 2
* DateFormat.LONG = 1
* DateFormat.MEDIUM = 2
* DateFormat.SHORT = 3
* @author Michael
* @version 1.0, 2007/03/09
*/
public class Test{
public static void main(String []args){
Date d = new Date();
String s;
/** Date类的格式: Sat Apr 16 13:17:29 CST 2006 */
System.out.println(d);
System.out.println("******************************************");
/** getDateInstance() */
/** 输出格式: 2006-4-16 */
s = DateFormat.getDateInstance().format(d);
System.out.println(s);
/** 输出格式: 2006-4-16 */
s = DateFormat.getDateInstance(DateFormat.DEFAULT).format(d);
System.out.println(s);
/** 输出格式: 2006年4月16日星期六 */
s = DateFormat.getDateInstance(DateFormat.FULL).format(d);
System.out.println(s);
/** 输出格式: 2006-4-16 */
s = DateFormat.getDateInstance(DateFormat.MEDIUM).format(d);
System.out.println(s);
/** 输出格式: 06-4-16 */
s = DateFormat.getDateInstance(DateFormat.SHORT).format(d);
System.out.println(s);
/** 输出格式: 2006-01-01 00:00:00 */
java.text.DateFormat format1 = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
s = format1.format(new Date());
System.out.println(s);
/** 输出格式: 2006-01-01 01:00:00 */
System.out.println((new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).format(new Date()));
/** 输出格式: 2006-01-01 13:00:00 */
System.out.println((new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
/** 输出格式: 20060101000000***/
java.text.DateFormat format2 = new java.text.SimpleDateFormat("yyyyMMddhhmmss");
s = format2.format(new Date());
System.out.println(s);
}
}
补充一下:
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
System.out.println("System Date: " + cal.get(Calendar.MONTH+1));
注意下,月份是从0开始的,要Calendar.MONTH+1才可以的。

相关文档
最新文档