java处理timestamp以及和date转换关系的总结
timestamp数据类型用法java

timestamp数据类型用法Java在Java编程语言中,timestamp是一种用于表示时间戳的数据类型。
时间戳是一个特定的日期和时间,通常以毫秒为单位表示自某个固定的参考时间点(通常是1970年1月1日午夜)以来的时间。
在本文中,我们将详细介绍Java中的timestamp数据类型的用法。
我们将讨论如何创建、操作和格式化时间戳,以及如何在不同的时间和日期库之间进行转换。
创建timestamp对象在Java中,我们可以使用java.sql.Timestamp类来表示时间戳。
要创建一个时间戳对象,我们可以使用以下方法之一:// 创建当前时间的时间戳Timestamp timestamp = new Timestamp(System.currentTimeMillis());// 创建指定日期和时间的时间戳Timestamp timestamp = Timestamp.valueOf("2022-01-01 12:00:00");第一个方法使用System.currentTimeMillis()获取当前时间的毫秒数,并将其传递给Timestamp构造函数来创建时间戳对象。
第二个方法使用Timestamp.valueOf()方法来将一个字符串表示的日期和时间转换为时间戳对象。
时间戳的操作一旦我们创建了一个时间戳对象,我们可以对其进行各种操作。
以下是一些常用的时间戳操作方法:•getTime():返回时间戳的毫秒数表示。
•before(Timestamp ts):检查一个时间戳是否在另一个时间戳之前。
•after(Timestamp ts):检查一个时间戳是否在另一个时间戳之后。
•compareTo(Timestamp ts):将两个时间戳进行比较,返回一个整数表示它们的相对顺序。
•setTime(long time):设置时间戳的毫秒数表示。
以下是使用这些方法的示例:Timestamp timestamp1 = Timestamp.valueOf("2022-01-01 12:00:00");Timestamp timestamp2 = Timestamp.valueOf("2022-01-02 12:00:00");long time1 = timestamp1.getTime(); // 获取时间戳的毫秒数boolean isBefore = timestamp1.before(timestamp2); // 检查timestamp1是否在time stamp2之前boolean isAfter = timestamp1.after(timestamp2); // 检查timestamp1是否在timest amp2之后int compareResult = pareTo(timestamp2); // 比较timestamp1和time stamp2的相对顺序timestamp1.setTime(System.currentTimeMillis()); // 设置时间戳的毫秒数为当前时间格式化timestamp在Java中,我们可以使用java.text.SimpleDateFormat类来格式化时间戳为指定的日期和时间字符串。
Java日期时间以及日期相互转换

Java⽇期时间以及⽇期相互转换Java⽇期时间,以及相互转化,供⼤家参考,具体内容如下package com.study.string;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;public class DateBase {public static void main(String[] args) throws ParseException {/** 获得当前时间*/Date date1 = new Date();long long1 = date1.getTime();//date类型,转为 long类型System.out.println(date1);//Sat Aug 26 08:36:36 GMT+08:00 2017System.out.println(long1);//1503708031359Calendar cale1 = Calendar.getInstance();date1 = cale1.getTime();//calendar 类型转为 date类型long1 = date1.getTime();System.out.println(cale1);System.out.println(date1);//Sat Aug 26 08:36:36 GMT+08:00 2017System.out.println(long1);/**设置时间*/long1 += 24*60*60*1000;date1.setTime(long1);System.out.println(date1);//Sun Aug 27 08:43:26 GMT+08:00 2017/** 格式化时间⽇期,⽆参数的默认格式,有参数的⾃定义格式。
timestamp java转年月日格式

timestamp java转年月日格式
在Java中,可以使用Java 8引入的java.time包来轻松地将时间戳转换为年月日格式。
以下是一个示例:
在这个示例中,我们首先使用Instant.ofEpochMilli(timestamp)从时间戳创建一个Instant对象。
然后,我们使用instant.atZone(ZoneId.systemDefault())将Instant转换为ZonedDateTime,这允许我们指定时区。
我们默认使用系统时区。
然后,我们使用DateTimeFormatter.ofPattern("yyyy-MM-dd")创建一个DateTimeFormatter对象,用于定义日期时间的格式。
在这个例子中,我们使用了"yyyy-MM-dd"格式,这将日期格式化为"年-月-日"的形式。
最后,我们使用zonedDateTime.format(formatter)将ZonedDateTime对象格式化为字符串,并打印出来。
1。
Java8中LocalDateTime与时间戳timestamp的互相转换

Java8中LocalDateTime与时间戳timestamp的互相转换Java8 LocalDateTime与timestamp转换将timestamp转为LocalDateTimepublic LocalDateTime timestamToDatetime(long timestamp){Instant instant = Instant.ofEpochMilli(timestamp);return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());}将LocalDataTime转为timestamppublic long datatimeToTimestamp(LocalDateTime ldt){long timestamp = ldt.toInstant(ZoneOffset.of("+8")).toEpochMilli();return timestamp;}我在⽹上还找到了另⼀个将datetime转为时间戳的⽅法:ZoneId zone = ZoneId.systemDefault();long timestamp = ldt.atZone(zone).toInstant().toEpochMilli();Java8的时间转为时间戳的⼤概的思路就是LocalDateTime先转为Instant,设置时区,然后转timestamp。
附⼀个Java8中的LocalDateTime⼯具类⼯具类package mon.utils.date;import java.time.*;import java.time.format.DateTimeFormatter;import java.time.temporal.ChronoUnit;import java.time.temporal.TemporalUnit;import java.util.Date;/** @author kingboy* @Date 2017/7/22 下午2:12* @Description LocalDateTimeUtils is used to Java8中的时间类*/public class LocalDateTimeUtils {//获取当前时间的LocalDateTime对象//LocalDateTime.now();//根据年⽉⽇构建LocalDateTime//LocalDateTime.of();//⽐较⽇期先后//LocalDateTime.now().isBefore(),//LocalDateTime.now().isAfter(),//Date转换为LocalDateTimepublic static LocalDateTime convertDateToLDT(Date date) {return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());}//LocalDateTime转换为Datepublic static Date convertLDTToDate(LocalDateTime time) {return Date.from(time.atZone(ZoneId.systemDefault()).toInstant());}//获取指定⽇期的毫秒public static Long getMilliByTime(LocalDateTime time) {return time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();}//获取指定⽇期的秒public static Long getSecondsByTime(LocalDateTime time) {return time.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();}//获取指定时间的指定格式public static String formatTime(LocalDateTime time,String pattern) {return time.format(DateTimeFormatter.ofPattern(pattern));}//获取当前时间的指定格式public static String formatNow(String pattern) {return formatTime(LocalDateTime.now(), pattern);}//⽇期加上⼀个数,根据field不同加不同值,field为ChronoUnit.*public static LocalDateTime plus(LocalDateTime time, long number, TemporalUnit field) {return time.plus(number, field);}//⽇期减去⼀个数,根据field不同减不同值,field参数为ChronoUnit.*public static LocalDateTime minu(LocalDateTime time, long number, TemporalUnit field){return time.minus(number,field);}/*** 获取两个⽇期的差 field参数为ChronoUnit.** @param startTime* @param endTime* @param field 单位(年⽉⽇时分秒)* @return*/public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) { Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));if (field == ChronoUnit.YEARS) return period.getYears();if (field == ChronoUnit.MONTHS) return period.getYears() * 12 + period.getMonths();return field.between(startTime, endTime);}//获取⼀天的开始时间,2017,7,22 00:00public static LocalDateTime getDayStart(LocalDateTime time) {return time.withHour(0).withMinute(0).withSecond(0).withNano(0);}//获取⼀天的结束时间,2017,7,22 23:59:59.999999999public static LocalDateTime getDayEnd(LocalDateTime time) {return time.withHour(23).withMinute(59).withSecond(59).withNano(999999999);}}测试类package mon.localdatetimeutils;import mon.utils.date.LocalDateTimeUtils;import org.junit.Test;import java.time.LocalDateTime;import java.time.temporal.ChronoUnit;import static mon.utils.date.LocalDateTimeUtils.getDayEnd;import static mon.utils.date.LocalDateTimeUtils.getDayStart;/*** @author kingboy* @Date 2017/7/22 下午7:16* @Description LocaDateTimeUtilsTest is used to 测试LocalDateTime⼯具*/public class LocaDateTimeUtilsTest {@Testpublic void format_test() {System.out.println(LocalDateTimeUtils.formatNow("yyyy年MM⽉dd⽇ HH:mm:ss"));}@Testpublic void betweenTwoTime_test() {LocalDateTime start = LocalDateTime.of(1993, 10, 13, 11, 11);LocalDateTime end = LocalDateTime.of(1994, 11, 13, 13, 13);System.out.println("年:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.YEARS));System.out.println("⽉:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.MONTHS));System.out.println("⽇:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.DAYS));System.out.println("半⽇:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.HALF_DAYS));System.out.println("⼩时:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.HOURS));System.out.println("分钟:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.MINUTES));System.out.println("秒:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.SECONDS));System.out.println("毫秒:" + LocalDateTimeUtils.betweenTwoTime(start, end, LIS));//=============================================================================================/*年:1⽉:13⽇:396半⽇:792⼩时:9506分钟:570362秒:34221720毫秒:34221720000*/}@Testpublic void plus_test() {//增加⼆⼗分钟System.out.println(LocalDateTimeUtils.formatTime(LocalDateTimeUtils.plus(LocalDateTime.now(),20,ChronoUnit.MINUTES), "yyyy年MM⽉dd⽇ HH:mm"));//增加两年System.out.println(LocalDateTimeUtils.formatTime(LocalDateTimeUtils.plus(LocalDateTime.now(),2,ChronoUnit.YEARS), "yyyy年MM⽉dd⽇ HH:mm"));//=============================================================================================/*2017年07⽉22⽇ 22:532019年07⽉22⽇ 22:33*/}@Testpublic void dayStart_test() {System.out.println(getDayStart(LocalDateTime.now()));System.out.println(getDayEnd(LocalDateTime.now()));//=============================================================================================/*2017-07-22T00:002017-07-22T23:59:59.999999999*/}}总结到此这篇关于Java8中LocalDateTime与时间戳timestamp互相转换的⽂章就介绍到这了,更多相关Java8 LocalDateTime与timestamp转换内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。
java中timestamp 时间戳转换时间的方法

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时间戳与⽇期相互转换⼯具详解本⽂为⼤家分享了java⽇期与时间戳相互转换⼤全,供⼤家参考,具体内容如下package com.crm.util;import java.math.BigDecimal;import java.text.DecimalFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;/*** @author DingJiaCheng* */public class DateFormatUtil {/*** 时间戳转⽇期* @param ms* @return*/public static Date transForDate(Integer ms){if(ms==null){ms=0;}long msl=(long)ms*1000;SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date temp=null;if(ms!=null){try {String str=sdf.format(msl);temp=sdf.parse(str);} catch (ParseException e) {e.printStackTrace();}}return temp;}/*** 获取晚上9点半的时间戳** @return*/public static int getTimes(int day, int hour, int minute) {Calendar cal = Calendar.getInstance();cal.add(Calendar.DATE, day);cal.set(Calendar.HOUR_OF_DAY, hour);cal.set(Calendar.SECOND, 0);cal.set(Calendar.MINUTE, minute);cal.set(LISECOND, 0);return (int) (cal.getTimeInMillis() / 1000);}/*** 获取当前时间往上的整点时间** @return*/public static int getIntegralTime() {Calendar cal = Calendar.getInstance();cal.add(Calendar.HOUR_OF_DAY, 1);cal.set(Calendar.SECOND, 0);cal.set(Calendar.MINUTE, 0);cal.set(LISECOND, 0);return (int) (cal.getTimeInMillis() / 1000);}public static int getIntegralTimeEnd() {Calendar cal = Calendar.getInstance();cal.set(Calendar.HOUR_OF_DAY, 24);cal.set(Calendar.SECOND, 0);cal.set(Calendar.MINUTE, 0);cal.set(LISECOND, 0);return (int) (cal.getTimeInMillis() / 1000);}/*** 时间戳转⽇期* @param ms* @return*/public static Date transForDate3(Integer ms){if(ms==null){ms=0;}long msl=(long)ms*1000;SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");Date temp=null;if(ms!=null){try {String str=sdf.format(msl);temp=sdf.parse(str);} catch (ParseException e) {e.printStackTrace();}}return temp;}/*** 时间戳转⽇期* @param ms* @return*/public static Date transForDate(Long ms){if(ms==null){ms=(long)0;}long msl=(long)ms*1000;SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date temp=null;if(ms!=null){try {String str=sdf.format(msl);temp=sdf.parse(str);} catch (ParseException e) {e.printStackTrace();}}return temp;}public static String transForDate1(Integer ms){String str = "";if(ms!=null){long msl=(long)ms*1000;SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if(ms!=null){try {str=sdf.format(msl);} catch (Exception e) {e.printStackTrace();}}}return str;}public static String transForDate2(Integer ms){String str = "";if(ms!=null){long msl=(long)ms*1000;SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");if(ms!=null){try {str=sdf.format(msl);} catch (Exception e) {e.printStackTrace();}}}return str;}public static String transForDate4(Integer ms){String str = "";if(ms!=null){long msl=(long)ms*1000;SimpleDateFormat sdf=new SimpleDateFormat("yyyy.MM.dd");if(ms!=null){try {str=sdf.format(msl);} catch (Exception e) {e.printStackTrace();}}}return str;}public static String transForDate5(Integer ms){String str = "";if(ms!=null){long msl=(long)ms*1000;SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");if(ms!=null){try {str=sdf.format(msl);} catch (Exception e) {e.printStackTrace();}}}return str;}public static String transForDateInChinese(Integer ms){String str = "";if(ms!=null){long msl=(long)ms*1000;SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM⽉dd⽇ HH:mm:ss"); if(ms!=null){try {str=sdf.format(msl);} catch (Exception e) {e.printStackTrace();}}}return str;}/*** ⽇期转时间戳* @param date* @return*/public static Integer transForMilliSecond(Date date){if(date==null) return null;return (int)(date.getTime()/1000);}/*** 获取当前时间戳* @return*/public static Integer currentTimeStamp(){return (int)(System.currentTimeMillis()/1000);/*** ⽇期字符串转时间戳* @param dateStr* @return*/public static Integer transForMilliSecond(String dateStr){Date date = DateFormatUtil.formatDate(dateStr);return date == null ? null : DateFormatUtil.transForMilliSecond(date);}/*** ⽇期字符串转时间戳* @param dateStr* @return*/public static Integer transForMilliSecond(String dateStr,String format){Date date = DateFormatUtil.formatDate(dateStr,format);return date == null ? null : DateFormatUtil.transForMilliSecond(date);}/*** ⽇期字符串转时间戳* @param dateStr* @param 格式如"yyyy-mm-dd"* @return*/public static Integer transForMilliSecondByTim(String dateStr,String tim){ SimpleDateFormat sdf=new SimpleDateFormat(tim);Date date =null;try {date = sdf.parse(dateStr);} catch (ParseException e) {e.printStackTrace();}return date == null ? null : DateFormatUtil.transForMilliSecond(date);}/*** 字符串转⽇期,格式为:"yyyy-MM-dd HH:mm:ss"* @param dateStr* @return*/public static Date formatDate(String dateStr){SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date result=null;try {result = sdf.parse(dateStr);} catch (ParseException e) {e.printStackTrace();}return result;}/*** 字符串转⽇期,格式为:"yyyy-MM-dd HH:mm:ss"* @param dateStr* @return*/public static Date formatDate(String dateStr,String format){SimpleDateFormat sdf=new SimpleDateFormat(format);Date result=null;try {result = sdf.parse(dateStr);} catch (ParseException e) {e.printStackTrace();}return result;}/*** ⽇期转字符串* @param date* @return*/public static String formatDate(Date date){SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String result=null;result = sdf.format(date);return result;* ⽇期转字符串* @param date* @return*/public static String formatDate(Date date,String format){SimpleDateFormat sdf=new SimpleDateFormat(format);String result=null;result = sdf.format(date);return result;}/*** 时间戳格式化输出(httl模版⽤)** @param ms 时间戳* @param format 格式化* @return*/public static String transForDate(Integer ms, String format){ String str = "";if(ms!=null){long msl=(long)ms*1000;SimpleDateFormat sdf=new SimpleDateFormat(format); if(!ms.equals(0)){try {str=sdf.format(msl);} catch (Exception e) {e.printStackTrace();}}}return str;}/*** 取BigDecimal类型数的整数或⼩数部分(httl模版⽤)** @param b 值* @param mode 模式 0取整 1去⼩数部分* @return*/public static String splitBigDecimal(BigDecimal b, int mode) { DecimalFormat df = new DecimalFormat("0.00");String s = df.format(b);if(mode==0){return s.split("\\.")[0];}else {return "."+s.split("\\.")[1];}}/*** 计算两个⽇期之间差的天数(httl模版⽤)** @param ts1 时间戳1* @param ts2 时间戳2* @return*/public static int caculate2Days(Integer ts1, Integer ts2) {Date firstDate = DateFormatUtil.transForDate(ts1);Date secondDate = DateFormatUtil.transForDate(ts2);Calendar calendar = Calendar.getInstance();calendar.setTime(firstDate);int dayNum1 = calendar.get(Calendar.DAY_OF_YEAR);calendar.setTime(secondDate);int dayNum2 = calendar.get(Calendar.DAY_OF_YEAR);return Math.abs(dayNum1 - dayNum2);}/*** 给⼿机加密中间四位加星号** @param mobile* @return*/public String mobileSerect(String mobile){if(!StringUtils.isBlank(mobile)){int between = mobile.length()/2;mobile = mobile.substring(0, between-2)+"****"+mobile.substring(between+2, mobile.length()); }return mobile;}/*** 给邮箱加密加星号** @param email* @return*/public String emailSerect(String email) {if(!StringUtils.isBlank(email)){int length = stIndexOf("@");email = email.substring(0, 2)+"****"+email.substring(length-2, email.length());}return email;}/*** BigDecimal类型数据相加** @param BigDecimal source* @param BigDecimal target* @return*/public BigDecimal sumBigDicimal(BigDecimal source, BigDecimal target) {source = source.add(target);return source;}/*** BigDecimal类型数据相加** @param BigDecimal source* @param BigDecimal target* @return*/public BigDecimal sumBigDicimalAndDouble(BigDecimal source, Double target) {BigDecimal new_target = new BigDecimal(target);source = source.add(new_target);return source;}/*** BigDecimal类型数据相减** @param BigDecimal source* @param BigDecimal target* @return*/public BigDecimal subBigDicimal(BigDecimal source, BigDecimal target) {source = source.subtract(target);return source;}/*** 获取传⼊时间和当前时间的时间差* @return*/public static Long getTimediff(int timeStamp){Date d1 = DateFormatUtil.transForDate(timeStamp);Date today = new Date();if(d1.getTime()<today.getTime()){return null;}return (d1.getTime()-today.getTime())/1000;}/*** 获取某周的第⼀天⽇期* @param week 0 当周 1 上⼀周 -1 下⼀周* @return*/public static String weekFirstDay(int week){Calendar c1 = Calendar.getInstance();int dow = c1.get(Calendar.DAY_OF_WEEK);c1.add(Calendar.DATE, -dow-7*(week-1)-5 );String d1 = new SimpleDateFormat("yyyy-MM-dd").format(c1.getTime());return d1+" 00:00:00";}/*** 当前时间加⼀年*/public static String addYear(int startTime){Date firstDate = DateFormatUtil.transForDate(startTime);Calendar calendar = Calendar.getInstance();calendar.setTime(firstDate);calendar.add(Calendar.YEAR,1);String d1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());return d1;}/*** 获取某周的最后⼀天⽇期* @param week* @return*/public static String weekLastDay(int week){Calendar c1 = Calendar.getInstance();int dow = c1.get(Calendar.DAY_OF_WEEK);c1.add(Calendar.DATE, -dow-7*(week-1)+1);String d1 = new SimpleDateFormat("yyyy-MM-dd").format(c1.getTime());return d1+" 23:59:59";}/*** 和当前时间⽐对* @return*/public static boolean greaterThanNow(int timeStamp){Date d1 = DateFormatUtil.transForDate(timeStamp);Date today = new Date();if(d1.getTime()>=today.getTime()){return true;}return false;}/*** HH:mm:ss格式时间转换为1970-01-01⽇的时间戳(也就是只有时间没有⽇期的情况要求使⽤时间戳表⽰时间) * @author DingJiaCheng* */public static int transFromTime(String time){return transForMilliSecond("1970-01-01 "+time,"yyyy-mm-dd HH:mm:ss");}/*** 时间戳转换为HH:mm:ss格式时间(⽇期去除)* @author DingJiaCheng* */public static String transToTime(int time){String s = new String(transForDate1(time));String ss[] = s.split(" ");return ss[1];}public static int transToChuo(String dateString){SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd");int res = 0;try {Date date=simpleDateFormat .parse(dateString);res = (int) date.getTime();} catch (ParseException e) {e.printStackTrace();}return res;}public static void main(String[] args) {//System.out.println(getIntegralTimeEnd());System.out.println(transForDate2(transForMilliSecond("2015-02-25 00:00:00")));//System.out.println(transForMilliSecond("2016-01-25","yyyy-mm-dd"));//System.out.println(transForDate1(transForMilliSecond("1970-01-01 00:00:00","yyyy-mm-dd HH:mm:ss"))); //System.out.println(currentTimeStamp());//System.out.println(transForDate(currentTimeStamp()));//System.out.println(new Date());//System.out.println(DateUtils.getDate());System.out.println(transFromTime("00:00:01"));System.out.println(transToTime(transFromTime("15:01:13")));}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
java日期互转:LocalDateTime、String、TimeStamp、Long、。。。

java⽇期互转:LocalDateTime、String、TimeStamp、Long、。
由于java版本的迭代,⼀个使⽤java开发的项⽬中可能出现多种⽇期对象,例如LocalDateTime、LocalDate、Date,不像C#只有⼀个DateTime,因此在各种⽇期格式或者对象之间的转换显得有点复杂,总是记不住,在需要⽤到时总是需要依靠搜索引擎,有点浪费时间,所以特意把常⽤的转换场景总结如下:1、 LocalDateTime转为String、TimeStamp、Long、Instant、 DateSystem.out.println("----------------LocalDateTime----------------");//LocalDateTime -> StringString localDateTimeToString = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));System.out.println("LocalDateTime -> String: " + localDateTimeToString);//LocalDateTime -> TimeStampTimestamp localDateTimeToTimeStamp = Timestamp.valueOf(LocalDateTime.now());System.out.println("LocalDateTime -> TimeStamp: " + localDateTimeToTimeStamp);//LocalDateTime -> LongLong localDateTimeToLong = Timestamp.valueOf(LocalDateTime.now()).getTime();System.out.println("LocalDateTime -> Long: " + localDateTimeToLong);//LocalDateTime -> InstantInstant localDateTimeToInstant = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant();System.out.println("LocalDateTime -> Instant: " + localDateTimeToInstant);//LocalDateTime -> DateDate LocalDateTimeToDate = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());System.out.println("LocalDateTime -> Date: " + LocalDateTimeToDate);2、String转为LocalDateTime、 DateSystem.out.println("----------------String----------------");//String -> LocalDateTimeLocalDateTime stringToLocalDateTime =LocalDateTime.parse("2018-03-11 15:30:11", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));System.out.println("String -> LocalDateTime: " + stringToLocalDateTime);//String -> Datetry {Date stringToDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2018-03-11 15:30:11");System.out.println("String -> Date: " + stringToDate);} catch (ParseException ex) {}3、Timestamp转为LocalDateTime、 DateSystem.out.println("---------------Timestamp-----------------");//Timestamp -> LocalDateTimeLocalDateTime timeStampToLocalDateTime =LocalDateTime.ofInstant(new Timestamp(1520754566856L).toInstant(), ZoneId.systemDefault());System.out.println("Timestamp -> LocalDateTime: " + timeStampToLocalDateTime);//Timestamp -> DateDate timestampToDate = Date.from(new Timestamp(1520754566856L).toInstant());System.out.println("Timestamp -> Date: " + timestampToDate);4、Long转为LocalDateTime、 DateSystem.out.println("---------------Long-----------------");//Long -> LocalDateTimeLocalDateTime longToLocalDateTime =LocalDateTime.ofInstant(Instant.ofEpochMilli(1520754566856L), ZoneId.systemDefault());System.out.println("Long -> LocalDateTime: " + longToLocalDateTime);//Long -> DateDate longToDate = new Date(1520754566856L);System.out.println("Long -> Date: " + longToDate);5、Instant转为LocalDateTime、 DateSystem.out.println("----------------Instant----------------");//Instant -> LocalDateTimeLocalDateTime instantToLocalDateTime = LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());System.out.println("Instant -> LocalDateTime: " + instantToLocalDateTime);//Instant -> DateDate instantToDate = Date.from(Instant.now());System.out.println("Instant -> Date: " + instantToDate);6、Date转为LocalDateTime、String、TimeStamp、Long、InstantSystem.out.println("----------------Date----------------");//Date -> StringString dateToString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());System.out.println("Date -> String: " + dateToString);//Date -> LocalDateTimeLocalDateTime dateToLocalDateTime = LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault()); System.out.println("Date -> LocalDateTime: " + dateToLocalDateTime);//Date -> TimestampTimestamp dateToTimestamp = new Timestamp(new Date().getTime());System.out.println("Date -> Timestamp: " + dateToTimestamp);//Date -> LongLong dateToLong = new Date().getTime();System.out.println("Date -> Long: " + dateToLong);//Date -> InstantInstant dateToInstant = new Date().toInstant();System.out.println("Date -> Instant: " + dateToInstant);。
【Java】时间戳与Date相互转换

【Java】时间戳与Date相互转换时间戳转Datepublic static void main(String[] args) {// 10位的秒级别的时间戳long time1 = 1527767665;String result1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time1 * 1000));System.out.println("10位数的时间戳(秒)--->Date:" + result1);Date date1 = new Date(time1*1000); //对应的就是时间戳对应的Date// 13位的秒级别的时间戳double time2 = 1515730332000d;String result2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time2);System.out.println("13位数的时间戳(毫秒)--->Date:" + result2);}10位数的时间戳(秒)--->Date:2018-05-31 19:54:2513位数的时间戳(毫秒)--->Date:2018-01-12 12:12:12尤其要注意上⾯10位的秒级别的时间戳时,不能⽤int来定义time1变量,否则会得到错误的结果:public static void main(String[] args) {// 10位的秒级别的时间戳int time1 = 1527767665; //错误做法String result1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time1 * 1000));System.out.println("10位数的时间戳(秒)--->Date:" + result1);}10位数的时间戳(秒)--->Date:1969-12-17 23:21:47Date转时间戳public static void main(String[] args) {//获取指定时间的时间戳,除以1000说明得到的是秒级别的时间戳(10位)long time = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse("2018-06-30 20:00:00", new ParsePosition(0)).getTime() / 1000;//获取时间戳long now1 = System.currentTimeMillis();long now2 = new Date().getTime();System.out.println("获取指定时间的时间戳:" + time);System.out.println("当前时间戳:" +now1);System.out.println("当前时间戳:" +now2);}获取指定时间的时间戳:1530360000当前时间戳:1527769494340当前时间戳:1527769494340格式化Datepublic static void main(String[] args) {//使⽤common-lang包下⾯的DateFormatUtils类String format1 = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");//使⽤最原始的SimpleDateFormat类String format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());System.out.println("格式化时间1:" + format1);System.out.println("格式化时间2:" + format2);}格式化时间1:2018-05-31 20:26:49格式化时间2:2018-05-31 20:26:49DateFormatUtils是ng3.time.DateFormatUtils下的,如果你的项⽬中没有,maven中引⼊下:<dependency><groupId>mons</groupId><artifactId>commons-lang3</artifactId><version>3.6</version></dependency>给⽇期加上指定时长⽐如,给现在的时间加上12个⼩时,这个需求也很常见,例如我做过的某个秒杀接⼝要返回剩余秒杀时间给前端,那么我就直接计算(⽐如秒杀持续时间为12⼩时):秒杀(倒计时)截⽌时间=(当前时间+12H)即可。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
String time = df.format(new Date()); Timestamp ts =
Timestamp.valueOf(time);
整理三: 在 ResultSet 中我们经常使用的 setDate 或 getDate 的数据类型是 java.sql.Date,而在平时 java 程序中我们一般习惯使用 java.util.Date。因 此在 DAO 层我们经常会碰到这俩种数据类型的相互转换,经过了一个下午的折 腾,鄙人对两者的转换方法做出了小小总结,希望大家不吝指教。 两者的关系
java.util.Date utilDate = new java.util.Date(sqlDate.getTime()); // sql -> util
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); // util -> sql
SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); java.util.Date date11 = df1.parse("2010-6-2 16:10:38.00"); String time = df1.format(date11); Timestamp ts = Timestamp.valueOf(time); System.out.println(ts); 输出:
public Date() { this(System.currentTimeMillis()); }
还发现一件怪异的事情: // String 转化成 date String str = "9-29-2001"; System.out.println(java.sql.Date.valueOf(str)); 输出: 0016-10-21
往数据库存储的时候可以接收 java.util.Date 类型 再用 getTime()方法得到代表那个 Date 对象的 long 值,再以这个 long 值 构造一个 Timestamp 对象 存进数据库中。
从存数据库里取的时候,可以先得到 Timestamp 用他的 getTime() 方法得到 long 值,再以这个 long 值构造一个 java.util.Date 对象,这样就可 以对这个 Date 对象操作了。不如说 new SimpleTimeFormat("yyyyy-MM-dd HH:mm:ss").format()等等
ng.Object | +---java.util.Date | +----java.sql.Date
从这个图中我们可以知道 java.sql.Date 是从 java.util.Date 继承过来的。
相互转换 1. 使用 getTime()函数 这两个类都提供了 getTime()函数,用于返回对应的毫秒数(long 类型)。利用 这个函数可以实现转换:
真是奇怪.
你从 公元 9 年 1 月 1 日算起,加上 2001 天,和 29 个月,时间就是 年 10 月 21 日
公元 16
Timestamp 是由 java.util.Date 和单独的毫微秒值组成。只有整数秒才会存储在
java.util.Date 组件中。小数秒(毫微秒)是独立存在的。传递 java.util.Date 类 型的值时,Timestamp.equals(Object) 方法永远不会返回 true,因为日期的毫微秒组 件是未知的。鉴于 Timestamp 类和上述 java.util.Date 类之间的不同,建议代码一 般不要将 Timestamp 值视为 java.util.Date 的实例。Timestamp 和 java.util.Date 之间的继承关系实际上指的是实现继承,而不是类型继承。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss SSS"); String time = sdf.format(Calendar.getInstance().getTime()); System.out.println(time); sql 包的 Date 类没有无参的构造函数,而 util 的 Date 类有无参的构造函数 java.util.Date date = new java.util.Date();是正确的 //Tue Jun 15 09:04:23 CST 2010 java.sql.Date date = new java.sql.Date();是错误的 但是 sql 包的 Date 有一个带 long 型参数的构造函数,因此可以使用以下方式
Timestamp now = new Timestamp(System.currentTimeMillis());//获取系统当
前时间 String str = df.format(now);
String 转化为 Timestamp:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
这样的构造是没有效率的,Timestamp 是 java.util.Date 的子类,可以这么做: new Timestamp(java.util.Date#getTime());
段箭*残箫 写道
还发现一件怪异的事情: // String 转化成 date String str = "9-29-2001"; System.out.println(java.sql.Date.valueOf(str)); 输出: 0016-10-21
ps:java.util.Date 类中的 getYear()要加上 1900 才可得到实际值,getMonth() 则要加上 1
有关 java 中的 Date,String,Timestamp 之间的转化问题
一.获取系统当前时间: 1.System.out.println(new Timestamp(new java.util.Date().getTime)); //包含时分 秒 2.System.out.println(new java.sql.Date(new java.util.Date().getTime)); //不包含时 分秒 3.通过格式化类获取任意格式的时间
整理二:
用 Timestamp 来记录日期时间还是很方便的,但有时候显示的时候是不需要小数 位后面的毫秒的,这样就需要在转换为 String 时重新定义格式。
Timestamp 转化为 String: SimpleDateFormat df = new
SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式,不显示毫秒
五. String 转化成 Timestamp SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); java.util.Date date11 = df1.parse("2010-6-2 16:10:38.00"); String time = df1.format(date11); Timestamp ts = Timestamp.valueOf(time); System.out.println(ts);
Java 中 Date 及 Timestamp 时间相关内容 (基本上看这一份就可以了)
java.util.date java.sql.date java.sql.timestamp
整理一: 这里的一片文章,我个人认为讲解的很详细,有对 java.sql.Date 的使用还有 困惑的请看。 java.sql.Date 只存储日期数据不存储时间数据 // 会丢失时间数据 preparedStatement.setDate(1, new java.sql.Date(date.getTime())); //可以这样来处理 preparedStatement.setTimestamp(1, new java.sql.Timestamp(new java.util.Date().getTime()));
2. 使用 SimpleDateFormat 类实现转换 SimpleDateFormat 是一个以国别敏感的方式格式化和分析数据的具体类。 它允 许格式化 (date -> text)、语法分析 (text -> date)和标准化。 SimpleDateFormat dateFormat = new SimpleDateFormate("yyyy-MM-dd HH:mm:ss"); java.util.Date utilDate = dateFormat.parse(sqlDate.toString());
//想要得到完整的数据,包括日期和时间,可以这样 java.util.Date d = resultSet.getTimestamp(1); //这样处理更合适一些,可以避免一些潜在 Timestamp 问题 java.util.Date d = new java.util.Date(resultSet.getTimestamp(1).getTime()); 自己补的话 这样的话:
2010-06-02 16:10:38.0
引用 还发现一件怪异的事情: // String 转化成 date String str = "9-29-2001"; System.out.println(java.sql.Date.valueOf(str));
Date#valueOf(String)的 String 格式都是 yyyy-mm-dd. 引用