java中时间格式的转换
- 格式:docx
- 大小:15.14 KB
- 文档页数:4
关于java实体类时间类型的格式化调整问题关于java bean在后台\转化为json交给前台时间类型格式调整的⽅法:1. ⾸先要引⼊fastjson依赖。
2. 在实体类上使⽤注解: @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8"),这⾥是精确到秒,如果只精确到天,就把上⾯注解的HH:mm:ss去掉。
package com.xjzt.waimai.pojo.weChatUser;import com.fasterxml.jackson.annotation.JsonFormat;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import org.apache.ibatis.type.Alias;import java.io.Serializable;import java.util.Date;@Data@AllArgsConstructor@NoArgsConstructor@Alias("weCharUser")public class WeCharUser implements Serializable {private String openId;private String nickName;private String gender;private String province;private String city;@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")private Date createTime;@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")private Date lastVisitTime;}。
java时分的正则表达式Java时分的正则表达式正则表达式是一种描述字符串模式的语法,可以用来匹配、查找和替换文本中的字符。
在Java中,可以使用正则表达式对字符串进行各种操作,如验证邮箱格式、提取手机号码、判断字符串是否为数字等。
本文将介绍Java中常用的时分正则表达式,并解释其用法和示例。
一、匹配时间格式的正则表达式1. 匹配24小时制的时间格式:HH:mm:ss正则表达式:^[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$示例:12:34:562. 匹配12小时制的时间格式:hh:mm:ss am/pm正则表达式:^(0[1-9]|1[0-2]):[0-5][0-9]:[0-5][0-9] (am|pm)$示例:09:45:30 am3. 匹配小时和分钟的时间格式:HH:mm正则表达式:^[0-2][0-9]:[0-5][0-9]$示例:20:154. 匹配12小时制的小时和分钟的时间格式:hh:mm am/pm正则表达式:^(0[1-9]|1[0-2]):[0-5][0-9] (am|pm)$示例:03:30 pm二、使用正则表达式的示例代码1. 验证时间格式是否正确:```javapublic boolean isValidTimeFormat(String time) {String regex = "^[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$"; return time.matches(regex);}```2. 提取时间字符串中的小时和分钟:```javapublic String extractHourAndMinute(String time) { String regex = "^(\\d{2}):(\\d{2}):(\\d{2})$";Pattern pattern = pile(regex);Matcher matcher = pattern.matcher(time);if (matcher.find()) {String hour = matcher.group(1);String minute = matcher.group(2);return hour + ":" + minute;}return null;}```三、注意事项和常见问题1. 在使用正则表达式时,需要使用Java的转义字符,如\需要写成\\。
date类型转年月日格式如何将日期类型转换为年月日格式[导语]日期类型是编程中常见的一种数据类型,它表示一个特定的日期和时间。
在某些情况下,我们需要将日期类型转换为特定的格式,例如年月日格式。
本文将为您介绍如何一步步将日期类型转换为年月日格式。
[第一步:了解日期类型]在开始转换之前,我们需要先了解日期类型。
常见的日期类型有Date、DateTime和Timestamp。
在不同的编程语言中,日期类型的表示方式可能会有些差异。
在本文中,我们以Java为例进行讲解。
在Java中,日期类型通常使用java.util.Date类来表示。
[第二步:获取日期类型对象]要进行日期格式转换,首先我们需要获得一个日期类型的对象。
可以通过不同的方式来获取日期类型对象。
例如,可以使用系统的当前日期和时间来创建一个新的日期对象,或者从数据库中获取日期类型的数据。
下面是一个示例代码,演示如何获取一个日期类型对象:javaimport java.util.Date;public class DateConversionExample {public static void main(String[] args) {Date currentDate = new Date();System.out.println("当前日期和时间:" + currentDate);}}在这个示例中,我们使用了java.util.Date类的无参构造方法创建了一个新的日期对象currentDate,并通过System.out.println()方法将其打印出来。
通过运行这段代码,我们可以获取到当前的日期和时间。
[第三步:格式化日期类型]获取到日期类型对象后,我们可以使用SimpleDateFormat类来对日期进行格式化。
SimpleDateFormat是Java中常用的日期格式化类,它提供了多种格式化模式,可以根据需要选择不同的模式来转换日期格式。
java2个时间格式间转换(原创实用版)目录1.Java 中时间格式的表示2.时间格式的转换方法3.具体转换实例正文在 Java 编程语言中,时间格式的表示主要依赖于`java.time`包中的`LocalDateTime`和`ZonedDateTime`类。
这两个类分别用于表示不带时区的本地日期时间以及带时区的日期时间。
在实际编程中,我们常常需要对这些时间格式进行转换。
接下来,我们就来学习一下如何在 Java 中进行时间格式的转换。
一、Java 中时间格式的表示在 Java 中,时间格式主要通过`DateTimeFormatter`类进行表示。
`DateTimeFormatter`类提供了一系列的静态方法,用于创建不同格式的日期时间表示。
例如,我们可以使用`DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")`创建一个表示“年 - 月-日时:分:秒”的格式。
二、时间格式的转换方法在 Java 中,我们可以通过`DateTimeFormatter`类的`parse()`和`format()`方法进行时间格式的转换。
`parse()`方法用于将字符串格式的时间转换为`LocalDateTime`或`ZonedDateTime`对象,而`format()`方法则用于将`LocalDateTime`或`ZonedDateTime`对象转换为字符串格式的时间。
以下是一个简单的转换实例:```javaimport java.time.LocalDateTime;import java.time.ZoneId;import java.time.format.DateTimeFormatter;public class TimeFormatConversion {public static void main(String[] args) {// 创建一个表示“年 - 月-日时:分:秒”的DateTimeFormatterDateTimeFormatter formatter =DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");// 定义一个字符串格式的时间String dateTimeStr = "2022-01-01 12:30:45";// 使用 parse() 方法将字符串格式的时间转换为LocalDateTime 对象LocalDateTime localDateTime =LocalDateTime.parse(dateTimeStr, formatter);// 使用 format() 方法将 LocalDateTime 对象转换为字符串格式的时间String convertedDateTimeStr =localDateTime.format(formatter);// 输出转换后的时间System.out.println("转换后的时间:" + convertedDateTimeStr);}}```三、具体转换实例以下是一个具体的转换实例,演示如何将一个表示“年 - 月-日时:分:秒”的时间格式转换为“时分:秒.毫秒”格式:```javaimport java.time.LocalDateTime;import java.time.format.DateTimeFormatter;public class TimeFormatConversion {public static void main(String[] args) {// 创建一个表示“年 - 月-日时:分:秒”的DateTimeFormatterDateTimeFormatter formatter =DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");// 定义一个字符串格式的时间String dateTimeStr = "2022-01-01 12:30:45";// 使用 parse() 方法将字符串格式的时间转换为LocalDateTime 对象LocalDateTime localDateTime =LocalDateTime.parse(dateTimeStr, formatter);// 使用 format() 方法将 LocalDateTime 对象转换为字符串格式的时间String convertedDateTimeStr =localDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS" ));// 输出转换后的时间System.out.println("转换后的时间:" + convertedDateTimeStr);}}```运行上述代码,输出结果为:```转换后的时间:12:30:45.000```以上就是 Java 中时间格式间转换的相关知识。
java 国际标准时间字符串转换-回复如何将国际标准时间字符串转换为其他格式的时间表示方式。
这篇文章将从最基本的概念开始,逐步解释如何进行转换,并提供实际的示例来帮助读者理解和应用这些概念。
首先,我们来了解一下国际标准时间的概念。
国际标准时间(简称UTC)是一种使用的全球标准时间,用于统一不同地区的时间表示方式。
它基于原子钟的测量结果,具有高度的精确性和可靠性。
国际标准时间通常以24小时制的方式表示,格式为hh:mm:ss。
例如,13:30:00表示下午1点30分。
现在假设我们有一个国际标准时间字符串"09:45:30",我们想将其转换为其他格式的时间表示方式,例如12小时制的时间、时间戳等等。
下面是一步一步的解释:1. 将字符串解析为时间对象:首先,我们需要将国际标准时间字符串解析为程序能够理解的时间对象。
在Java中,可以使用SimpleDateFormat 类来完成这个任务。
以下是一个示例代码:javaString timeString = "09:45:30";SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");Date time = sdf.parse(timeString);在这个示例中,我们使用SimpleDateFormat来定义一个格式为"HH:mm:ss"的时间模板,然后将时间字符串解析为一个Date对象。
2. 转换为12小时制的时间表示方式:如果我们想将时间表示为12小时制的方式,我们需要使用另一个时间格式模板"hh:mm:ss a"。
以下是一个示例代码:javaSimpleDateFormat sdf12 = new SimpleDateFormat("hh:mm:ss a"); String time12 = sdf12.format(time);System.out.println(time12);在这个示例中,我们创建了另一个SimpleDateFormat对象,使用"hh:mm:ss a"作为时间格式模板。
java中timestamp 时间戳转换时间的方法(实用版4篇)目录(篇1)1.java中timestamp时间戳转换时间的方法2.时间戳的概念和作用3.java中常用的时间戳转换方法4.时间戳转换方法的优缺点5.总结正文(篇1)一、java中timestamp时间戳转换时间的方法在Java中,timestamp时间戳是一种常用的时间表示方式,可以记录时间的起始点。
时间戳通常用于记录事件发生的时间,例如日志记录、数据传输等。
在Java中,可以使用以下方法将timestamp转换为可读的时间格式:1.DateFormat类:DateFormat类可以将timestamp转换为可读的时间格式。
例如,可以使用以下代码将timestamp转换为Date对象:Date date = new Date(timestamp);2.Calendar类:Calendar类可以获取当前时间的各个部分,例如年、月、日、时、分、秒等。
可以使用以下代码将timestamp转换为Calendar 对象:Calendar calendar = Calendar.getInstance();calendar.setTimeInMillis(timestamp);3.SimpleDateFormat类:SimpleDateFormat类可以根据指定的格式将timestamp转换为可读的时间格式。
例如,可以使用以下代码将timestamp转换为String类型的时间格式:String time = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss").format(new Date(timestamp));二、时间戳的概念和作用时间戳是指计算机系统自动生成的一个序列号,用于记录时间的起始点。
在计算机系统中,时间戳通常用于记录事件发生的时间,例如日志记录、数据传输等。
时间戳可以用于比较两个时间点之间的差异,例如计算两个事件之间的时间间隔。
java 国际标准时间字符串转换在Java编程中,我们经常需要将日期和时间从一种格式转换为另一种格式。
特别是当我们需要与国际标准时间(UTC)进行交互时,我们经常需要将本地时间转换为UTC时间。
在Java中,可以使用java.time包中的类来进行这种转换。
一、背景介绍Java8引入了新的日期和时间API,即java.time包。
这个包提供了简单易用的API来处理日期和时间。
它包括LocalDate、LocalTime、LocalDateTime、ZonedDateTime等类,可以方便地处理各种日期和时间相关的操作。
二、问题阐述在Java应用程序中,我们经常需要将本地时间转换为国际标准时间(UTC)。
例如,当与远程服务器进行通信时,我们需要将本地时间转换为UTC时间以便正确处理时间戳。
此外,在处理跨时区的数据时,也需要进行这样的转换。
三、解决方案为了将本地时间转换为国际标准时间(UTC),我们可以使用java.time包中的ZonedDateTime类和DateTimeFormatter类。
ZonedDateTime类提供了当前的日期和时间以及所在的时区信息。
通过将它转换为没有时区信息的ZonedDateTime对象,我们就可以得到相应的UTC时间。
以下是一个示例代码:```javaimportjava.time.ZoneId;importjava.time.ZonedDateTime;importjava.time.format.DateTimeFormatter;publicclassMain{publicstaticvoidmain(String[]args){//获取当前本地时间ZoneIdlocalZone=ZoneId.of("Asia/Shanghai");//替换为你的本地时区ZonedDateTimelocalDateTime=ZonedDateTime.now(localZone);System.out.println("Localtime:"+localDateTime);//将本地时间转换为UTC时间ZoneIdutcZone=ZoneId.of("Z");//Z代表UTC时区ZonedDateTimeutcDateTime=localDateTime.withZoneSameInstan t(utcZone);System.out.println("UTCtime:"+utcDateTime);}}```在这个示例中,我们首先获取了当前本地时间,并将其存储在ZonedDateTime对象中。
java中各种时间格式的转化时间和日期中常用到的几个类:java.util.Date,java.util.Calendar,java.util.GregorainCalendar,java.text.DateFormat,java.text.SimpleDateFormatjava.util.Date :表示特定瞬间,精确到毫秒一天是24 * 60 * 60 = 86400 秒世界时(UT 或UTC) , 格林威治时间(GMT), 格林威治时(GMT)和世界时(UT)是相等的,格林威治时(GMT) 是标准的"民间"称呼, 世界时(UT) 是相同标准的科学称呼。
UTC 和UT 的区别是:UTC 是基于原子时钟的,UT 是基于天体观察的。
(中文版的jdk 真是好啊,跟科普教材是的,呵呵)常用的构造方法:Date();Date(long date)(long date) 表示从标准基准时间(称为"历元" epoch ,即1970.1.100:00:00 GMT)经历的毫秒数。
还有一些构造方法已经deprecated 了主要的方法:(介绍几个常用的,详细的查询jdk 文档)boolean after(Date when) 测试日期在此日期之后。
boolean before(Date when) 测试日期在此日期之前。
Object clone() 返回此对象的副本long getTime() 返回自1970.1.1 00:00:00 GMT 后,此对象表示的毫秒数void setTime(long time) 设置此Date 对象,以表示1970 年1 月1 日00:00:00 GMT 以后time 毫秒的时间点。
String toString() 将Date 对象转化成以下形式的String:dow mon dd hh:mm:ss zzz yyyy其中:dow 是一周中的某一天(Sun, Mon, Tue, Wed, Thu, Fri, Sat)。
Java8中时间的字符串和Long时间戳互转1、取当前时间戳Long millisecond = Instant.now().toEpochMilli(); // 精确到毫秒Long second = Instant.now().getEpochSecond();// 精确到秒2、将Long类型的时间戳转成字符串/*** 将Long类型的时间戳转换成String 类型的时间格式,时间格式为:yyyy-MM-dd HH:mm:ss*/public static String timeToString(Long time){Assert.notNull(time, "time is null");DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");return ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time),ZoneId.systemDefault()));}3、时间字符串转成Long类型的时间戳/*** 将字符串转⽇期成Long类型的时间戳,格式为:yyyy-MM-dd HH:mm:ss*/public static Long timeToLong(String time) {Assert.notNull(time, "time is null");DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");LocalDateTime parse = LocalDateTime.parse("2019-11-28 08:52:50", ftf);return LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();}4、时间转换Utils/*** 将Long类型的时间戳转换成String 类型的时间格式,时间格式为:yyyy-MM-dd HH:mm:ss*/public static String timeToString(Long time, String format){Assert.notNull(time, "time is null");// "yyyy-MM-dd HH:mm:ss"DateTimeFormatter formatString = DateTimeFormatter.ofPattern(format);return formatString.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()));}/*** 将字符串转⽇期成Long类型的时间戳,格式为:yyyy-MM-dd HH:mm:ss*/public static Long timeToLong(String time) {Assert.notNull(time, "time is null");DateTimeFormatter formatString = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");LocalDateTime parse = LocalDateTime.parse("2019-11-28 08:52:50", formatString);return LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();}/*** localDate 格式化*/public static String localDateFormat(LocalDate localDate, String format){Assert.notNull(localDate, "time is null");// "yyyy-MM-dd HH:mm:ss"String localDateStr = DateTranslate.timeToString(localDate2Second(localDate), format);return localDateStr;}/*** localDate 格式化*/public static String localDateTimeFormat(LocalDateTime localDateTime, String format){Assert.notNull(localDateTime, "time is null");// "yyyy-MM-dd HH:mm:ss"String localDateTimeStr = DateTranslate.timeToString(localDateTime2Second(localDateTime), format);return localDateTimeStr;}/*** 取本⽉第⼀天*/public static LocalDate firstDayOfThisMonth() {LocalDate today = LocalDate.now();return today.with(TemporalAdjusters.firstDayOfMonth());}/*** 取本⽉第⼀天*/public static LocalDate firstDayOfLastMonth() {LocalDate today = LocalDate.now();today = today.minusMonths(1);return today.with(TemporalAdjusters.firstDayOfMonth());}/*** 取本⽉第N天*/public static LocalDate dayOfThisMonth(int n) {LocalDate today = LocalDate.now();return today.withDayOfMonth(n);}/*** 取本⽉最后⼀天*/public static LocalDate lastDayOfThisMonth() {LocalDate today = LocalDate.now();return today.with(stDayOfMonth());}/*** 获取本周⼀*/public static LocalDateTime firstDayOfWeek(Long date) {// long转LocalDateTimeLocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date), ZoneId.systemDefault());return localDateTime.with(DayOfWeek.MONDAY);}/*** 获取上周⼀*/public static LocalDateTime firstDayOfLastWeek(Long date) {// long转LocalDateTimeLocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date), ZoneId.systemDefault());LocalDateTime localDateTime1 = localDateTime.plusDays(-7);return localDateTime1.with(DayOfWeek.MONDAY);}/*** 获取上周⼀*/public static LocalDateTime lastDay(Long date) {// long转LocalDateTimeLocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(date), ZoneId.systemDefault()); LocalDateTime localDateTime1 = localDateTime.plusDays(-1);return localDateTime1;}/*** 取本⽉第⼀天的开始时间*/public static LocalDateTime startOfThisMonth() {return LocalDateTime.of(firstDayOfThisMonth(), LocalTime.MIN);}/*** 取本⽉最后⼀天的结束时间*/public static LocalDateTime endOfThisMonth() {return LocalDateTime.of(lastDayOfThisMonth(), LocalTime.MAX);}/** LocalDate转时间戳 */public static Long localDate2Second(LocalDate localDate) {return LocalDateTime.of(localDate, LocalTime.MIN).toInstant(ZoneOffset.ofHours(8)).getEpochSecond();}/** LocalDate转时间戳 */public static Long localDateTime2Second(LocalDateTime localDateTime) {return localDateTime.toEpochSecond(ZoneOffset.of("+8"));}java 8 Localdate常⽤API====================================正确答案==================================getYear() int获取当前⽇期的年份getMonth() Month 获取当前⽇期的⽉份对象getMonthValue() int获取当前⽇期是第⼏⽉getDayOfWeek() DayOfWeek 表⽰该对象表⽰的⽇期是星期⼏getDayOfMonth() int表⽰该对象表⽰的⽇期是这个⽉第⼏天getDayOfYear() int表⽰该对象表⽰的⽇期是今年第⼏天withYear(int year) LocalDate 修改当前对象的年份withMonth(int month) LocalDate 修改当前对象的⽉份withDayOfMonth(int dayOfMonth) LocalDate 修改当前对象在当⽉的⽇期isLeapYear() boolean是否是闰年lengthOfMonth() int这个⽉有多少天lengthOfYear() int该对象表⽰的年份有多少天(365或者366)plusYears(long yearsToAdd) LocalDate 当前对象增加指定的年份数plusMonths(long monthsToAdd) LocalDate 当前对象增加指定的⽉份数plusWeeks(long weeksToAdd) LocalDate 当前对象增加指定的周数plusDays(long daysToAdd) LocalDate 当前对象增加指定的天数minusYears(long yearsToSubtract) LocalDate 当前对象减去指定的年数minusMonths(long monthsToSubtract) LocalDate 当前对象减去注定的⽉数minusWeeks(long weeksToSubtract) LocalDate 当前对象减去指定的周数minusDays(long daysToSubtract) LocalDate 当前对象减去指定的天数compareTo(ChronoLocalDate other) int⽐较当前对象和other对象在时间上的⼤⼩,返回值如果为正,则当前对象时间较晚,isBefore(ChronoLocalDate other) boolean⽐较当前对象⽇期是否在other对象⽇期之前isAfter(ChronoLocalDate other) boolean⽐较当前对象⽇期是否在other对象⽇期之后isEqual(ChronoLocalDate other) boolean⽐较两个⽇期对象是否相等。
java中国标准时间转换yymmdd方法在Java编程中,我们经常需要进行日期和时间的转换和处理。
其中一个常见的需求是将中国标准时间(CST)转换为一个特定的格式,比如yymmdd(年份的后两位+月份+日期)。
下面是一种Java方法,可以用来实现这个转换。
```javaimport java.text.SimpleDateFormat;import java.util.Date;import java.util.TimeZone;public class CSTConverter {public static String convertToYYMMDD(Date date) {// 设置时区为中国(东八区)TimeZone cstTimezone = TimeZone.getTimeZone("Asia/Shanghai");SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd");dateFormat.setTimeZone(cstTimezone);// 将传入的日期对象按照指定格式进行格式化String convertedDate = dateFormat.format(date);// 返回转换后的字符串return convertedDate;}public static void main(String[] args) {// 测试示例Date current = new Date();String convertedDate = convertToYYMMDD(current);System.out.println("当前日期转换后的结果为:" + convertedDate);}}```在上述代码中,我们使用了`SimpleDateFormat`类来指定日期格式,并使用`TimeZone`类来设置时区为中国(东八区)。
Java时间⽇期格式转换Date转String和String转Date 1 Java时间格式转换⼤全23import java.text.*;4import java.util.Calendar;5public class VeDate {6/**7* 获取现在时间8*9* @return返回时间类型 yyyy-MM-dd HH:mm:ss10*/11public static Date getNowDate() {12 Date currentTime = new Date();13 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");14 String dateString = formatter.format(currentTime);15 ParsePosition pos = new ParsePosition(8);16 Date currentTime_2 = formatter.parse(dateString, pos);17return currentTime_2;18 }19/**20* 获取现在时间21*22* @return返回短时间格式 yyyy-MM-dd23*/24 DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");25 DateFormat format 2= new SimpleDateFormat("yyyy年MM⽉dd⽇ HH时mm分ss秒");26 Date date = null;27 String str = null;2829// String转Date30 str = "2007-1-18";31try {32 date = format1.parse(str);33 data = format2.parse(str);34 } catch (ParseException e) {35 e.printStackTrace();36 }37/**38* 获取现在时间39*40* @return返回字符串格式 yyyy-MM-dd HH:mm:ss41*/42public static String getStringDate() {43 Date currentTime = new Date();44 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");45 String dateString = formatter.format(currentTime);46return dateString;47 }48/**49* 获取现在时间50*51* @return返回短时间字符串格式yyyy-MM-dd52*/53public static String getStringDateShort() {54 Date currentTime = new Date();55 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");56 String dateString = formatter.format(currentTime);57return dateString;58 }59/**60* 获取时间⼩时:分;秒 HH:mm:ss61*62* @return63*/64public static String getTimeShort() {65 SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");66 Date currentTime = new Date();67 String dateString = formatter.format(currentTime);68return dateString;69 }70/**71* 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss72*73* @param strDate74* @return75*/76public static Date strToDateLong(String strDate) {77 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");81 }82/**83* 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss84*85* @param dateDate86* @return87*/88public static String dateToStrLong(java.util.Date dateDate) {89 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");90 String dateString = formatter.format(dateDate);91return dateString;92 }93/**94* 将短时间格式时间转换为字符串 yyyy-MM-dd95*96* @param dateDate97* @param k98* @return99*/100public static String dateToStr(java.util.Date dateDate) {101 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");102 String dateString = formatter.format(dateDate);103return dateString;104 }105/**106* 将短时间格式字符串转换为时间 yyyy-MM-dd107*108* @param strDate109* @return110*/111public static Date strToDate(String strDate) {112 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");113 ParsePosition pos = new ParsePosition(0);114 Date strtodate = formatter.parse(strDate, pos);115return strtodate;116 }117/**118* 得到现在时间119*120* @return121*/122public static Date getNow() {123 Date currentTime = new Date();124return currentTime;125 }126/**127* 提取⼀个⽉中的最后⼀天128*129* @param day130* @return131*/132public static Date getLastDate(long day) {133 Date date = new Date();134long date_3_hm = date.getTime() - 3600000 * 34 * day;135 Date date_3_hm_date = new Date(date_3_hm);136return date_3_hm_date;137 }138/**139* 得到现在时间140*141* @return字符串 yyyyMMdd HHmmss142*/143public static String getStringToday() {144 Date currentTime = new Date();145 SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HHmmss"); 146 String dateString = formatter.format(currentTime);147return dateString;148 }149/**150* 得到现在⼩时151*/152public static String getHour() {153 Date currentTime = new Date();154 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 155 String dateString = formatter.format(currentTime);156 String hour;157 hour = dateString.substring(11, 13);158return hour;159 }160/**161* 得到现在分钟165public static String getTime() {166 Date currentTime = new Date();167 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");168 String dateString = formatter.format(currentTime);169 String min;170 min = dateString.substring(14, 16);171return min;172 }173/**174* 根据⽤户传⼊的时间表⽰格式,返回当前时间的格式如果是yyyyMMdd,注意字母y不能⼤写。
Java前后端时间格式的转化⽅式JsonFormat、DateTimeFormat使⽤从数据库获取时间传到前端进⾏展⽰的时候,我们有时候可能⽆法得到⼀个满意的时间格式的时间⽇期,在数据库中显⽰的是正确的时间格式,获取出来却变成了很丑的时间戳,@JsonFormat注解很好的解决了这个问题,我们通过使⽤@JsonFormat 可以很好的解决:后台到前台时间格式保持⼀致的问题。
其次,另⼀个问题是,我们在使⽤WEB服务的时,可能会需要⽤到,传⼊时间给后台,⽐如注册新⽤户需要填⼊出⽣⽇期等,这个时候前台传递给后台的时间格式同样是不⼀致的,⽽我们的与之对应的便有了另⼀个注解,@DataTimeFormat便很好的解决了这个问题,接下来记录⼀下具体的@JsonFormat与DateTimeFormat的使⽤过程。
@JsonFormat导⼊依赖<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.8.8</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.8.8</version></dependency><dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.9.13</version></dependency>在你需要查询出来的时间的数据库字段对应的实体类的属性上添加 @JsonFormat@Data@Api("升级⽇志返回值")public class UpgradeLogRes {@ApiModelProperty("升级⽇志id")private Long id;@ApiModelProperty("版本名称")private String name;@ApiModelProperty("发布⽇期")@JsonFormat(pattern = "yyyy-MM-dd")private Date postDate;@ApiModelProperty("内容⽇志")private String contentLog;@ApiModelProperty("发布状态")private Integer postStatus;@ApiModelProperty("内容⽇志Url")private String contentLogUrl;}注:@JsonFormat(pattern=“yyyy-MM-dd”,timezone = “GMT+8”)pattern:是你需要转换的时间⽇期的格式timezone:是时间设置为东⼋区,避免时间在转换中有误差提⽰:@JsonFormat注解可以在属性的上⽅,同样可以在属性对应的get⽅法上,两种⽅式没有区别@DateTimeFormat导⼊依赖:@DateTimeFormat的使⽤和@jsonFormat差不多,⾸先需要引⼊是spring还有jodatime,spring我就不贴了<dependency><groupId>joda-time</groupId><artifactId>joda-time</artifactId><version>2.3</version></dependency>在controller层我们使⽤spring mvc 表单⾃动封装映射对象时,我们在对应的接收前台数据的对象的属性上加@DateTimeFormat@DateTimeFormat(pattern = "yyyy-MM-dd")@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")private Date symstarttime;@DateTimeFormat(pattern = "yyyy-MM-dd")@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")private Date symendtime;我这⾥就只贴这两个属性了,这⾥我两个注解都同时使⽤了,因为我既需要取数据到前台,也需要前台数据传到后台,都需要进⾏时间格式的转换,可以同时使⽤总结⼀下:注解@JsonFormat主要是后台到前台的时间格式的转换注解@DataFormAT主要是前后到后台的时间格式的转换java前后端Date接收1.前端传Date对象将其转为“yyyy-MM-dd HH:mm:ss”的字符串,后台⽤@DateTimeFormat(pattern=“yyyy-MM-dd HH:mm:ss”)格式化Date属性2.后台返回给前端Date传的是时间戳,⽤@JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss”, timezone = “GMT+8”)对其格式化,timezone是⽤于调整时区的属性(东⼋区),不加的话得到的时间会⽐实际的少8个⼩时@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")private Date startTime;3.时间⽐较:mybaties :startTime, endTime是经过@DateTimeFormat格式后的Date对象<if test="startTime != null">and alarm.createTime >= #{startTime}</if><if test="endTime != null">and alarm.createTime <= #{endTime}</if>以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
Java 日期时间Date类型,long类型,String类型表现形式的转换1、java.util.Date类型转换成long类型java.util.Date dt = new Date();System.out.println(dt.toString()); //java.util.Date的含义long lSysTime1 = dt.getTime() / 1000; //得到秒数,Date类型的getTime()返回毫秒数java.util.Date dt = new Date();System.out.println(dt.toString()); //java.util.Date的含义long lSysTime1 = dt.getTime() / 1000; //得到秒数,Date类型的getTime()返回毫秒数2、由long类型转换成Date类型SimpleDateFormat sdf= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");//前面的lSysTime是秒数,先乘1000得到毫秒数,再转为java.util.Date 类型java.util.Date dt = new Date(lSysTime1 * 1000);String sDateTime = sdf.format(dt); //得到精确到秒的表示:08/31/200621:08:00System.out.println(sDateTime);SimpleDateFormat sdf= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");//前面的lSysTime是秒数,先乘1000得到毫秒数,再转为java.util.Date 类型java.util.Date dt = new Date(lSysTime1 * 1000);String sDateTime = sdf.format(dt); //得到精确到秒的表示:08/31/2006 21:08:00System.out.println(sDateTime);//注意HH与hh含认不同,HH表示以24小时制取,hh表示以12小时制取常用的格式的含义,摘自Jdk,注意大小写的含义通常是不同的:3、"08/31/2006 21:08:00"格式的String转换java.util.Date类型String sDt = "08/31/2006 21:08:00";SimpleDateFormat sdf= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");Date dt2 = sdf.parse(sDt);//继续转换得到秒数的long型long lTime = dt2.getTime() / 1000;String sDt = "08/31/2006 21:08:00";SimpleDateFormat sdf= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");Date dt2 = sdf.parse(sDt);//继续转换得到秒数的long型long lTime = dt2.getTime() / 1000;//注意HH与hh含认不同,HH表示以24小时制取,hh表示以12小时制取常用的格式的含义,摘自Jdk,注意大小写的含义通常是不同的:字母含义示例y Y ear 1996;96 哪一年M Month in year J uly;Jul;07 一年中的哪一月m Minute in hour 30 一个小时中的第几分钟w Week in year 27 一年中的第几个星期W Week in month 2 一个月中的第几个星期D Day in year 189 一年中的第几天d Day in month 10 一个月中的第几天H Hour in day (0-23) 0 一天中的第几个小时(24小时制)h Hour in am/pm (1-12) 12 一天中上午、下午的第几个小时(12小时制)S Millisecond 978 毫秒数s Second in minute 55 一分钟的第几秒字母含义示例y Y ear 1996;96 哪一年M Month in year J uly;Jul;07 一年中的哪一月m Minute in hour 30 一个小时中的第几分钟w Week in year 27 一年中的第几个星期W Week in month 2 一个月中的第几个星期D Day in year 189 一年中的第几天d Day in month 10 一个月中的第几天H Hour in day (0-23) 0 一天中的第几个小时(24小时制)h Hour in am/pm (1-12) 12 一天中上午、下午的第几个小时(12小时制)S Millisecond 978 毫秒数s Second in minute 55 一分钟的第几秒4、系统当前时间long lSysTime2 = System.currentTimeMillis(); //得到毫秒表示的系统当前时间long lSysTime2 = System.currentTimeMillis(); //得到毫秒表示的系统当前时间。
JAVA⽇期格式转换SimpleDateFormat使⽤String转DateString STANDARD_DATE_FORMAT_UTC = "";//设置⽇期时间格式SimpleDateFormat simpleDateFormat = new SimpleDateFormat(STANDARD_DATE_FORMAT);//创建⽇期时间模板String formatStr = "",//拿到与STANDARD_DATE_FORMAT_UTC⼀样的时间字符串Date date = new Date();date = simpleDateFormat.parse(formatStr);//根据模板把字符串转换成标准Date();Date类型转StringString STANDARD_DATE_FORMAT_UTC = "";//设置⽇期时间格式SimpleDateFormat simpleDateFormat = new SimpleDateFormat(STANDARD_DATE_FORMAT);//创建⽇期时间模板Date date = new Date();//拿到⼀个⽇期类型的值String str = "";str = simpleDateFormat.format(date);//根据模板把时间格式转换成特定格式的字符串⽰例:(yyyy-MM-dd'T'HH:mm:ss.SSS'Z')String STANDARD_DATE_FORMAT_UTC = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";SimpleDateFormat sdf_input = new SimpleDateFormat(STANDARD_DATE_FORMAT_UTC);//输⼊格式String str=inMap.get("createDate").toString();sdf_input.setTimeZone(TimeZone.getTimeZone("GMT"));try {Date date = sdf_input.parse(str);epStaff.setCreateDate(str);}catch (Exception e){System.out.println(e);}Mybatis将⽇期时间格式数据持久到数据库中通常⽤到的util包中的Date()类型在持久到数据库中时会报⽆法转换的错误,要使⽤new java.sql.Date(date.getTime());java.sql包下给出三个与数据库相关的⽇期时间类型,分别是:Date:表⽰⽇期,只有年⽉⽇,没有时分秒。
java中localdatetime转date几种方法-回复如何在Java中将LocalDateTime转换为Date——几种方法Introduction:在Java编程中,我们经常需要在LocalDateTime和Date之间进行转换。
LocalDateTime是Java 8引入的新类,用于表示一个不可变的日期时间对象。
而Date则是Java早期版本中用于表示日期和时间的类。
因此,当我们需要在新旧版本之间进行数据转换时,就需要对它们进行互相转换。
在本文中,我们将一步一步介绍如何使用几种方法将LocalDateTime转换为Date。
方法一:使用java.util.Date的from()方法java.util.Date类提供了一个静态方法from(),可以从Instant对象创建一个Date对象。
因为LocalDateTime没有提供直接转换为Instant对象的方法,所以我们首先需要将LocalDateTime转换为ZonedDateTime对象,然后再将其转换为Instant对象,最后使用from()方法创建Date对象。
下面是具体的代码示例:javaimport java.time.LocalDateTime;import java.time.ZoneId;import java.time.ZonedDateTime;import java.util.Date;public class LocalDateTimeToDateConverter {public static void main(String[] args) {LocalDateTime localDateTime = LocalDateTime.now();ZonedDateTime zonedDateTime =localDateTime.atZone(ZoneId.systemDefault());Instant instant = zonedDateTime.toInstant();Date date = Date.from(instant);System.out.println("LocalDateTime: " + localDateTime);System.out.println("Date: " + date);}}在上述代码中,我们首先获取当前的LocalDateTime对象。
java对世界各个时区(Time Zone)的通用转换处理方法.在进行国际性软件项目开发的过程中,有时候会碰到一些比较特殊的要求。
比如:比如说,你做的是个购物网站(假设服务器放在中国上海),当全世界客户在你的网站上下订单买东西后,往往希望看到客户所在地下单时间,比如说我是个美国纽约人,我在你的网站上下单后,你给我看到一个上海的下单时间,会觉得非常的奇怪。
众所周知,纽约时间相对上海时间大约要晚13小时,如果让客户看到本地时区的时间,将变得更加符合客户的时间观念,使得客户理解比较方便。
其实,java中早已考虑过世界时区(Time Zone)这个问题,并给出了比较合理的解决方法,可以比较方便的进行世界时区时间的转化,将一个时区的时间转换成另一个时区的时间。
可以看看下面的的实际例子(运行例子的main()方法)。
关于如何知道客户所在的时区,可以根据客户所在的ip或者用户注册提供的国家来计算出所在的时区。
Java代码 01./* 02.* Cre atedon 2005-6-10 03. * Auth or st ephen04. * E mailzhouj ianqi ang A T gma il DO T com05. * C opyRi ght(C)2005-2008 , Al l rig hts r eserv ed. 06.*/ 07.pa ckage com.soft4j.uti lity;08. 09.im portjava.text.Parse Excep tion;10.imp ort j ava.t ext.S imple DateF ormat; 11.im portjava.util.Date;12.imp ort j ava.u til.G regor ianCa lenda r; 13.i mport java.util.Time Zone;14.imp ort j ava.u til.V ector; 15. 16.i mport com.soft4j.log.Log;17. 18./**19. *与日期、时间相关的一些常用工具方法. 20.* <p>21. * 日期(时间)的常用格式(form ater)主要有:<br>22. * yy yy-MM-dd H H:mm:ss <b r> 23. *24. *@auth or st ephen25. * @versi on 1.0.0 26.*/ 27.pu blicfinal clas s Dat eTool { 28.29./** 30. *对日期(时间)中的日进行加减计算. <b r> 31. *例子: <br> 32.*如果Da te类型的d为 2005年8月20日,那么 <br>33. * c alcul ateBy Date(d,-10)的值为2005年8月10日<br>34.* 而ca lcula teByD ate(d,+10)的值为2005年8月30日<br> 35.*36. * @param d 37. *日期(时间). 38.* @par am am ount39.* 加减计算的幅度.+n=加n天;-n=减n天.40. * @r eturn计算后的日期(时间). 41. */42. publi c sta tic D ate c alcul ateBy Date(Dated, in t amo unt){ 43. retu rn ca lcula te(d, Greg orian Calen dar.D ATE,amoun t); 44.}45. 46. pub lic s tatic Date calc ulate ByMin ute(D ate d, int amou nt) {47. retur n cal culat e(d,Grego rianC alend ar.MI NUTE, amou nt);48. } 49. 50. pu blicstati c Dat e cal culat eByYe ar(Da te d, intamoun t) {51. r eturn calc ulate(d, G regor ianCa lenda r.YEA R, am ount); 52. } 53.54. /** 55.*对日期(时间)中由field参数指定的日期成员进行加减计算. <br>56. * 例子: <b r> 57. *如果Dat e类型的d为 2005年8月20日,那么 <br>58. * ca lcula te(d,Grego rianC alend ar.YE AR,-10)的值为1995年8月20日 <br>59. * 而c alcul ate(d,Greg orian Calen dar.Y EAR,+10)的值为2015年8月20日 <br> 60. * 61.* @pa ram d62. * 日期(时间).63. * @param fiel d64. * 日期成员. <br>65. * 日期成员主要有: <b r> 66. *年:Gr egori anCal endar.YEAR <br>67. * 月:Greg orian Calen dar.M ONTH<br>68.* 日:Grego rianC alend ar.DA TE <b r> 69. *时:Gr egori anCal endar.HOUR <br>70. * 分:Greg orian Calen dar.M INUTE <br>71. * 秒:Greg orian Calen dar.S ECOND <br>72. * 毫秒:Gre goria nCale ndar.MILLI SECON D <br>73. * @param amou nt 74. *加减计算的幅度.+n=加n个由参数fi eld指定的日期成员值;-n=减n个由参数fiel d代表的日期成员值.75. * @r eturn计算后的日期(时间). 76. */77. priva te st aticDatecalcu late(Dated, in t fie ld, i nt am ount) { 78. if(d == null) 79. retur n nul l; 80. Gre goria nCale ndarg = n ew Gr egori anCal endar(); 81. g.setGr egori anCha nge(d); 82. g.a dd(fi eld,amoun t); 83. re turng.get Time(); 84. }85.86. /**87.* 日期(时间)转化为字符串.88. * 89.* @par am fo rmate r90. * 日期或时间的格式.91.* @pa ram a Date92.* ja va.ut il.Da te类的实例. 93. *@retu rn 日期转化后的字符串. 94.*/95. publ ic st aticStrin g dat e2Str ing(S tring form ater, Date aDat e) {96. i f (fo rmate r ==null|| "".equa ls(fo rmate r)) 97. ret urn n ull;98. i f (aD ate == nul l) 99. retu rn nu ll; 100. r eturn (new Simp leDat eForm at(fo rmate r)).f ormat(aDat e); 101. } 102.103. /** 104.* 当前日期(时间)转化为字符串. 105.*106. *@para m for mater107. * 日期或时间的格式.108. * @r eturn日期转化后的字符串.109. */110. publ ic st aticStrin g dat e2Str ing(S tring form ater) { 111. re turndate2Strin g(for mater, new Date());112. } 113.114. /**115. * 获取当前日期对应的星期数.116. *<br>1=星期天,2=星期一,3=星期二,4=星期三,5=星期四,6=星期五,7=星期六117. * @retur n 当前日期对应的星期数118.*/119. pub lic s tatic intdayOf Week() { 120. G regor ianCa lenda r g = newGrego rianC alend ar();121. intret = g.ge t(jav a.uti l.Cal endar.DAY_OF_WE EK);122. g = n ull;123. retur n ret; 124. }125. 126.127. /** 128.* 获取所有的时区编号. <b r> 129.*排序规则:按照AS CII字符的正序进行排序. <br> 130.* 排序时候忽略字符大小写.131. * 132.* @re turn所有的时区编号(时区编号已经按照字符[忽略大小写]排序).133. */ 134.p ublic stat ic St ring[] fec thAll TimeZ oneId s() {135. Vect or v= new Vect or();136. Stri ng[]ids = Time Zone.getAv ailab leIDs(); 137. f or (i nt i= 0;i < i ds.le ngth; i++) { 138. v.a dd(id s[i]); 139. } 140. j ava.u til.C ollec tions.sort(v, S tring.CASE_INSE NSITI VE_OR DER);141. v.co pyInt o(ids); 142. v= nul l; 143. re turnids;144. } 145.146. /**147. * 测试的main方法. 148.* 149.* @par am ar gc 150.*/151. pub lic s tatic void main(Stri ng[]argc) { 152.153. S tring[] id s = f ecthA llTim eZone Ids(); 154. Str ing n owDat eTime =dat e2Str ing("yyyy-MM-dd HH:m m:ss"); 155. Sy stem.out.p rintl n("Th e tim e Asi a/Sha nhaiis "+ now DateT ime);//程序本地运行所在时区为[A sia/S hanha i] 156. //显示世界每个时区当前的实际时间157. for(int i=0;i<ids.lengt h;i++){ 158. Sys tem.o ut.pr intln(" *" + i ds[i] + "="+ s tring2Time zoneD efaul t(now DateT ime,i ds[i])); 159. } 160. //显示程序运行所在地的时区161.Sys tem.o ut.pr intln("Tim eZone.getD efaul t().g etID()=" +TimeZ one.g etDef ault().get ID()); 162. }163. 164. /**165. *将日期时间字符串根据转换为指定时区的日期时间. 166.* 167.* @par am sr cForm ater168. * 待转化的日期时间的格式.169. *@para m src DateT ime 170.* 待转化的日期时间. 171.* @par am ds tForm ater172. * 目标的日期时间的格式.173. * @param dstT imeZo neId174. * 目标的时区编号. 175.*176. *@retu rn 转化后的日期时间. 177.*/178. pub lic s tatic Stri ng st ring2Timez one(S tring srcF ormat er, 179. St ringsrcDa teTim e, St ringdstFo rmate r, St ringdstTi meZon eId){ 180. if(srcF ormat er == null || "".equ als(s rcFor mater)) 181. ret urn n ull;182. if (s rcDat eTime == n ull || "".equal s(src DateT ime))183. retur n nul l; 184. if (dst Forma ter == nul l ||"".eq uals(dstFo rmate r)) 185. re turnnull;186. if (dstTi meZon eId == nul l ||"".eq uals(dstTi meZon eId))187. retur n nul l; 188. Si mpleD ateFo rmatsdf = newSimpl eDate Forma t(src Forma ter);189. try{ 190. intdiffT ime = getD iffTi meZon eRawO ffset(dstT imeZo neId); 191. Date d =sdf.p arse(srcDa teTim e); 192. lo ng no wTime = d.getTi me();193. longnewNo wTime = no wTime - di ffTim e; 194. d = newDate(newNo wTime); 195. ret urn d ate2S tring(dstF ormat er, d); 196. }catch (Par seExc eptio n e){ 197. Log.outpu t(e.t oStri ng(), Log.STD_E RR);198. r eturn null; 199. } f inall y { 200. sd f = n ull;202. }203. 204. /**205. *获取系统当前默认时区与UTC的时间差.(单位:毫秒)206. *207. * @retur n 系统当前默认时区与UTC的时间差.(单位:毫秒)208. */209. priv ate s tatic intgetDe fault TimeZ oneRa wOffs et(){ 210. ret urn T imeZo ne.ge tDefa ult().getR awOff set(); 211. }212. 213. /**214. *获取指定时区与UTC的时间差.(单位:毫秒) 215.*216. *@para m tim eZone Id 217.*时区I d218. *@retu rn 指定时区与UT C的时间差.(单位:毫秒) 219.*/ 220. pr ivate stat ic in t get TimeZ oneRa wOffs et(St ringtimeZ oneId) { 221. r eturn Time Zone.getTi meZon e(tim eZone Id).g etRaw Offse t();222. } 223.224. /**225. * 获取系统当前默认时区与指定时区的时间差.(单位:毫秒)226. * 227. * @p aramtimeZ oneId228. * 时区Id229. * @r eturn系统当前默认时区与指定时区的时间差.(单位:毫秒) 230. */231. priv ate s tatic intgetDi ffTim eZone RawOf fset(Strin g tim eZone Id) {232. retu rn Ti meZon e.get Defau lt().getRa wOffs et()233. -TimeZ one.g etTim eZone(time ZoneI d).ge tRawO ffset(); 234. } 235.236. /** 237.* 将日期时间字符串根据转换为指定时区的日期时间.238. * 239. * @p aramsrcDa teTim e240. *待转化的日期时间.241. * @param dstT imeZo neId242. * 目标的时区编号. 243.*244. *@retu rn 转化后的日期时间. 245.* @see #str ing2T imezo ne(St ring, Stri ng, S tring, Str ing)247.p ublic stat ic St ringstrin g2Tim ezone Defau lt(St ringsrcDa teTim e, 248. Str ing d stTim eZone Id) {249. retu rn st ring2Timez one("yyyy-MM-dd HH:m m:ss", src DateT ime,250. "y yyy-M M-ddHH:mm:ss", dstT imeZo neId); 251. }252. 253.}。
1.将日期类型转换为格式的字符串类型java.util.Date中的日期Date Date date = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String time=sdf.format(date);2.将字符串类型的转换为指定格式的日期类型(java.util.Date)String time = "2009-7-29 14:28:12";DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date = df.parse(time);这里需要抛出ParseException异常若将java.util.Date类型转换成java.sql.Date时,只需添加一行代码java.sql.Date sqlDate = new java.sql.Date(date.getTime());3.使用java.sql.Timestamp在java程序中rs.getDate()时获取日期的时、分、秒String str = "";String format="yyyy-MM-dd HH:mm:ss";try {//这里与数据库的连接已经省略,获得PreparedStatement的对象psmtResultSet rs = psmt.executeQuery();while(rs.next()){Timestamp ts = rs.getTimestamp("pdate");SimpleDateFormat sdf = new SimpleDateFormat(format);str = sdf.format(ts);System.out.println(str);}} catch (SQLException e) {e.printStackTrace(); } ......SimpleDateFormat的用法://SimpleDateFormat中的parse方法可以把String型的字符串转换成特定格式的date类型import java.text.*;import java.util.*;public class TestDate {public static void main(String[] args) {String dStr = "2001.12.12-08.23.21";Date d = null;SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd-HH.mm.ss");try {d = sdf.parse(dStr);} catch (ParseException pe) {System.out.println(pe.getMessage());}System.out.println(d);System.out.println(d.getTime());}}//下面的format方法可以将date型的数据转换成特定的String型字符串public class FormatDateTime {public static void main(String[] args) {SimpleDateFormat myFmt=new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");SimpleDateFormat myFmt1=new SimpleDateFormat("yy/MM/dd HH:mm");SimpleDateFormat myFmt2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//等价于now.toLocaleString()SimpleDateFormat myFmt3=new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒E ");SimpleDateFormat myFmt4=new SimpleDateFormat("一年中的第D 天一年中第w个星期一月中第W个星期在一天中k时z时区");Date now=new Date();System.out.println(myFmt.format(now));System.out.println(myFmt1.format(now));System.out.println(myFmt2.format(now));System.out.println(myFmt3.format(now));System.out.println(myFmt4.format(now));System.out.println(now.toGMTString());System.out.println(now.toLocaleString());System.out.println(now.toString());}}效果:2004年12月16日17时24分27秒04/12/16 17:242004-12-16 17:24:272004年12月16日17时24分27秒星期四一年中的第351 天一年中第51个星期一月中第3个星期在一天中17时CST时区16 Dec 2004 09:24:27 GMT2004-12-16 17:24:27Thu Dec 16 17:24:27 CST 2004下面是个JavaBean:public class FormatDateTime {public static String toLongDateString(Date dt){SimpleDateFormat myFmt=new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss 秒E ");return myFmt.format(dt);}public static String toShortDateString(Date dt){SimpleDateFormat myFmt=new SimpleDateFormat("yy年MM月dd日HH时mm分");return myFmt.format(dt);}public static String toLongTimeString(Date dt){SimpleDateFormat myFmt=new SimpleDateFormat("HH mm ss SSSS");return myFmt.format(dt);}public static String toShortTimeString(Date dt){SimpleDateFormat myFmt=new SimpleDateFormat("yy/MM/dd HH:mm");return myFmt.format(dt);}public static void main(String[] args) {Date now=new Date();System.out.println(FormatDateTime.toLongDateString(now));System.out.println(FormatDateTime.toShortDateString(now));System.out.println(FormatDateTime.toLongTimeString(now));System.out.println(FormatDateTime.toShortTimeString(now));}}调用的main 测试结果:2004年12月16日17时38分26秒星期四04年12月16日17时38分17 38 26 096504/12/16 17:3824小时制时间显示:public class Datetime {public static void main(String args[]){java.util.Date current=new java.util.Date();java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String c=sdf.format(current);System.out.println(c);}}12小时制时间显示:public class Datetime {public static void main(String args[]){java.util.Date current=new java.util.Date();java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");String c=sdf.format(current);System.out.println(c);}}。