使用SimpleDateFormat来实现格式化日期

import java.text.SimpleDateFormat;
import java.util.Date;public class DateFormatExample {public static void main(String args[]) {Date today = new Date();System.out.println("今天 is : " + today);SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy");String date = DATE_FORMAT.format(today);System.out.println("今天 in dd-MM-yyyy format : " + date);DATE_FORMAT = new SimpleDateFormat("dd/MM/yy");date = DATE_FORMAT.format(today);System.out.println("今天 in dd/MM/yy pattern : " + date);//formatting Date with time informationDATE_FORMAT = new SimpleDateFormat("dd-MM-yy:HH:mm:SS");date = DATE_FORMAT.format(today);System.out.println("今天 in dd-MM-yy:HH:mm:SS : " + date);//SimpleDateFormat example - Date with timezone informationDATE_FORMAT = new SimpleDateFormat("dd-MM-yy:HH:mm:SS Z");date = DATE_FORMAT.format(today);System.out.println("今天 in dd-MM-yy:HH:mm:SSZ : " + date);}}

但是

DateFormat 的所有实现,包括 SimpleDateFormat 都不是线程安全的,因此你不应该在多线程序中使用,除非是在对外线程安全的环境中使用,如 将 SimpleDateFormat 限制在 ThreadLocal 中。如果你不这么做,在解析或者格式化日期的时候,可能会获取到一个不正确的结果。因此,从日期、时间处理的所有实践来说,我强力推荐 joda-time 库。

Joda-Time

主要的特点包括:

1. 易于使用:Calendar让获取"正常的"的日期变得很困难,使它没办法提供简单的方法,而Joda-Time能够 直接进行访问域并且索引值1就是代表January。
2. 易于扩展:JDK支持多日历系统是通过Calendar的子类来实现,这样就显示的非常笨重而且事实 上要实现其它日历系统是很困难的。Joda-Time支持多日历系统是通过基于Chronology类的插件体系来实现。

3. 提供一组完整的功能:它打算提供 所有关系到date-time计算的功能.Joda-Time当前支持8种日历系统,而且在将来还会继续添加,有着比JDK Calendar更好的整体性能等等。

封装joda-time的时间工具类:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeZone;
import org.joda.time.Days;
import org.joda.time.LocalDate;import com.sun.istack.internal.Nullable;/*** 使用joda的时间工具类* @author soyoungboy**/
public class DateUtils {public static final long SECOND = 1000; // 1秒 java已毫秒为单位public static final long MINUTE = SECOND * 60; // 一分钟public static final long HOUR = MINUTE * 60; // 一小时public static final long DAY = HOUR * 24; // 一天public static final long WEEK = DAY * 7; // 一周public static final long YEAR = DAY * 365; // 一年public static final String FORMAT_TIME = "yyyy-MM-dd HH:mm:ss"; // 默认时间格式public static final String FORMAT_TIME_MINUTE = "yyyy-MM-dd HH:mm"; // 默认时间格式public static final String FORTER_DATE = "yyyy-MM-dd"; // 默认日期格式private static final Map<Integer, String> WEEK_DAY = new HashMap<Integer, String>();static {WEEK_DAY.put(7, "星期六");WEEK_DAY.put(1, "星期天");WEEK_DAY.put(2, "星期一");WEEK_DAY.put(3, "星期二");WEEK_DAY.put(4, "星期三");WEEK_DAY.put(5, "星期四");WEEK_DAY.put(6, "星期五");}/*** 获取当前系统时间* * @return yyyy-MM-dd HH:mm:ss*/public static String getCurrentTime() {DateTime dt = new DateTime();String time = dt.toString(FORMAT_TIME);return time;}/*** 获取系统当前时间按照指定格式返回* * @param pattern*            yyyy/MM/dd hh:mm:a* @return*/public static String getCurrentTimePattern(String pattern) {DateTime dt = new DateTime();String time = dt.toString(pattern);return time;}/*** 获取当前日期* * @return*/public static String getCurrentDate() {DateTime dt = new DateTime();String date = dt.toString(FORTER_DATE);return date;}/*** 获取当前日期按照指定格式* * @param pattern* @return*/public static String getCurrentDatePattern(String pattern) {DateTime dt = new DateTime();String date = dt.toString(pattern);return date;}/*** 按照时区转换时间* * @param date* @param timeZone*            时区* @param parrten* @return*/@Nullablepublic static String format(Date date, TimeZone timeZone, String parrten) {if (date == null) {return null;}SimpleDateFormat sdf = new SimpleDateFormat(parrten);sdf.setTimeZone(timeZone);return sdf.format(date);}/*** 获取指定时间* * @param year*            年* @param month*            月* @param day*            天* @param hour*            小时* @param minute*            分钟* @param seconds*            秒* @return yyyy-MM-dd HH:mm:ss*/public static String getPointTime(Integer year, Integer month, Integer day, Integer hour, Integer minute,Integer seconds) {DateTime dt = new DateTime(year, month, day, hour, minute, seconds);String date = dt.toString(FORMAT_TIME);return date;}/*** * @param year*            年* @param month*            月* @param day*            天* @param hour*            小时* @param minute*            分钟* @param seconds*            秒* @param parrten*            自定义格式* @return parrten*/public static String getPointTimePattern(Integer year, Integer month, Integer day, Integer hour, Integer minute,Integer seconds, String parrten) {DateTime dt = new DateTime(year, month, day, hour, minute, seconds);String date = dt.toString(parrten);return date;}/*** 获取指定日期* * @param year* @param month* @param day* @return*/public static String getPointDate(Integer year, Integer month, Integer day) {LocalDate dt = new LocalDate(year, month, day);String date = dt.toString(FORTER_DATE);return date;}/*** 获取指定日期 返回指定格式* * @param year* @param month* @param day* @param parrten* @return*/public static String getPointDatParrten(Integer year, Integer month, Integer day, String parrten) {LocalDate dt = new LocalDate(year, month, day);String date = dt.toString(parrten);return date;}/*** 获取当前是一周星期几* * @return*/public static String getWeek() {DateTime dts = new DateTime();String week = null;switch (dts.getDayOfWeek()) {case DateTimeConstants.SUNDAY:week = "星期日";break;case DateTimeConstants.MONDAY:week = "星期一";break;case DateTimeConstants.TUESDAY:week = "星期二";break;case DateTimeConstants.WEDNESDAY:week = "星期三";break;case DateTimeConstants.THURSDAY:week = "星期四";break;case DateTimeConstants.FRIDAY:week = "星期五";break;case DateTimeConstants.SATURDAY:week = "星期六";default:break;}return week;}/*** 获取指定时间是一周的星期几* * @param year* @param month* @param day* @return*/public static String getWeekPoint(Integer year, Integer month, Integer day) {LocalDate dts = new LocalDate(year, month, day);String week = null;switch (dts.getDayOfWeek()) {case DateTimeConstants.SUNDAY:week = "星期日";break;case DateTimeConstants.MONDAY:week = "星期一";break;case DateTimeConstants.TUESDAY:week = "星期二";break;case DateTimeConstants.WEDNESDAY:week = "星期三";break;case DateTimeConstants.THURSDAY:week = "星期四";break;case DateTimeConstants.FRIDAY:week = "星期五";break;case DateTimeConstants.SATURDAY:week = "星期六";break;default:break;}return week;}/*** 格式化日期* * @param date* @return yyyy-MM-dd HH:mm:ss*/@Nullablepublic static String format(Date date) {if (date == null) {return null;}SimpleDateFormat format = new SimpleDateFormat(FORMAT_TIME);return format.format(date);}/*** 格式化日期字符串* * @param date*            日期* @param pattern*            日期格式* @return*/@Nullablepublic static String format(Date date, String pattern) {if (date == null) {return null;}SimpleDateFormat format = new SimpleDateFormat(pattern);return format.format(date);}/*** 解析日期* * @param date*            日期字符串* @param pattern*            日期格式* @return*/@Nullablepublic static Date parse(String date, String pattern) {if (date == null) {return null;}Date resultDate = null;try {resultDate = new SimpleDateFormat(pattern).parse(date);} catch (ParseException e) {}return resultDate;}/*** 解析日期yyyy-MM-dd HH:mm:ss* * @param date*            日期字符串* @return*/@Nullablepublic static Date parse(String date) {if (date == null) {return null;}try {return new SimpleDateFormat(FORMAT_TIME).parse(date);} catch (ParseException e) {return null;}}/*** 解析日期 yyyy-MM-dd HH:mm:ss* * @param timestamp* @return*/public static String format(Long timestamp, String pattern) {String dateStr = "";if (null == timestamp || timestamp.longValue() < 0) {return dateStr;}try {Date date = new Date(timestamp);SimpleDateFormat format = new SimpleDateFormat(pattern);dateStr = format.format(date);} catch (Exception e) {// ignore
        }return dateStr;}/*** 解析日期 yyyy-MM-dd HH:mm:ss* * @param timestamp* @return*/public static String format(Long timestamp) {String dateStr = "";if (null == timestamp || timestamp.longValue() < 0) {return dateStr;}try {Date date = new Date(timestamp);SimpleDateFormat format = new SimpleDateFormat(FORMAT_TIME);dateStr = format.format(date);} catch (Exception e) {// ignore
        }return dateStr;}/*** 获取当前时间前几天时间,按指定格式返回* * @param days* @return*/public static String forwardDay(Integer days, String format) {DateTime dt = new DateTime();DateTime y = dt.minusDays(days);return y.toString(format);}/*** 获取当前时间前几天时间* * @param days* @return*/public static Date forwardDay(Integer days) {DateTime dt = new DateTime();DateTime y = dt.minusDays(days);return y.toDate();}/*** 获取指定时间之后或者之前的某一天00:00:00 默认返回当天* * @param days* @return*/public static Date day00(Integer days, String date, String zimeZone) throws Throwable {DateTime dt;TimeZone timeZone;try {if (isBlank(zimeZone)) {timeZone = TimeZone.getDefault();} else {timeZone = TimeZone.getTimeZone(zimeZone);}if (isBlank(date)) {dt = new DateTime().withZone(DateTimeZone.forTimeZone(timeZone)).toLocalDateTime().toDateTime();} else {dt = new DateTime(date).withZone(DateTimeZone.forTimeZone(timeZone)).toLocalDateTime().toDateTime();}} catch (Exception e) {throw new Throwable(e);}DateTime y = dt.minusDays(days).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0);return y.toDate();}/*** 获取指定时间之后或者之前的某一天23:59:59 默认返回当天* * @param days*            偏移量* @return*/public static Date day59(Integer days, String date, String zimeZone) throws Throwable {DateTime dt;TimeZone timeZone;try {if (isBlank(zimeZone)) {timeZone = TimeZone.getDefault();} else {timeZone = TimeZone.getTimeZone(zimeZone);}if (isBlank(date)) {dt = new DateTime().withZone(DateTimeZone.forTimeZone(timeZone)).toLocalDateTime().toDateTime();} else {dt = new DateTime(date).withZone(DateTimeZone.forTimeZone(timeZone)).toLocalDateTime().toDateTime();}} catch (Exception e) {throw new Throwable(e);}DateTime y = dt.minusDays(days).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59);return y.toDate();}/*** 计算两个时间相差多少天* * @param startDate* @param endDate* @return*/@Nullablepublic static Integer diffDay(Date startDate, Date endDate) {if (startDate == null || endDate == null) {return null;}DateTime dt1 = new DateTime(startDate);DateTime dt2 = new DateTime(endDate);int day = Days.daysBetween(dt1, dt2).getDays();return Math.abs(day);}/*** 获取某月之前,之后某一个月最后一天,24:59:59* * @return*/public static Date lastDay(Date date, Integer month) {DateTime dt1;if (month == null) {month = 0;}if (date == null) {dt1 = new DateTime().minusMonths(month);} else {dt1 = new DateTime(date).minusMonths(month);}DateTime lastDay = dt1.dayOfMonth().withMaximumValue().withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59);return lastDay.toDate();}/*** 获取某月月之前,之后某一个月第一天,00:00:00* * @return*/public static Date firstDay(Date date, Integer month) {DateTime dt1;if (month == null) {month = 0;}if (date == null) {dt1 = new DateTime().minusMonths(month);} else {dt1 = new DateTime(date).minusMonths(month);}DateTime lastDay = dt1.dayOfMonth().withMinimumValue().withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0);return lastDay.toDate();}public static Date addDay(Date date, int offset) {DateTime dt1;if (date == null) {dt1 = new DateTime().plusDays(offset);return dt1.toDate();}dt1 = new DateTime(date).plusDays(offset);return dt1.toDate();}/*** 传入日期时间与当前系统日期时间的比较, 若日期相同,则根据时分秒来返回 , 否则返回具体日期* * @return 日期或者 xx小时前||xx分钟前||xx秒前*/@Nullablepublic static String getNewUpdateDateString(Date now, Date createDate) {if (now == null || createDate == null) {return null;}Long time = (now.getTime() - createDate.getTime());if (time > (24 * 60 * 60 * 1000)) {return time / (24 * 60 * 60 * 1000) + "天前";} else if (time > (60 * 60 * 1000)) {return time / (60 * 60 * 1000) + "小时前";} else if (time > (60 * 1000)) {return time / (60 * 1000) + "分钟前";} else if (time >= 1000) {return time / 1000 + "秒前";}return "刚刚";}/*** * @Title: isBlank* @Description: TODO(判断字符串是否为空或长度为0 或由空格组成)* @param @param str* @param @return 设定文件* @return boolean 返回类型* @throws*/public static boolean isBlank(String str) {return (str == null || str.trim().length() == 0);}public static void main(String[] args) throws Throwable {System.out.println(lastDay(new Date(),2));System.out.println(firstDay(null,0));TimeZone zone1=TimeZone.getTimeZone("GMT+8");TimeZone zone2=TimeZone.getTimeZone("GMT-5");System.out.println(format(new Date(),zone1,FORMAT_TIME));System.out.println(format(new Date(),zone2,FORMAT_TIME));System.out.println(format(day00(0,"2017-5-11","GMT+0")));System.out.println(format(day00(0,"2017-5-11","GMT+8")));System.out.println(format(day00(0,"2017-5-11","GMT-8")));Date date1 =parse("2017-05-11 17:53:52");System.out.println(diffDay(date1,new Date()));DateTime dateTime = new DateTime().withDayOfWeek(1);DateTime dateTime1 = new DateTime().withDayOfWeek(7).withTime(0, 0,0, 0);System.out.println(format(dateTime.toDate()));System.out.println(format(dateTime1.toDate()));System.out.println(format(new Date(), "MM/dd"));}}

其中测试代码结果:

Fri Jun 30 23:59:59 GMT+08:00 2017
Tue Aug 01 00:00:00 GMT+08:00 2017
2017-08-28 19:47:28
2017-08-28 06:47:28
2017-05-10 00:00:00
2017-05-11 00:00:00
2017-05-10 00:00:00
109
2017-08-28 19:47:29
2017-09-03 00:00:00
08/28

转载于:https://www.cnblogs.com/androidsuperman/p/7451384.html

面试题1 -- Java 中,怎么在格式化的日期中显示时区?相关推荐

  1. 如何在Java 8中使用LocalDateTime格式化/解析日期-示例教程

    Java项目中的常见任务之一是将日期格式化或解析为String,反之亦然. 解析日期表示您有一个表示日期的字符串,例如" 2017-08-3",并且要将其转换为表示Java中日期的 ...

  2. java文本框默认格式化,XJL:Swing中的格式化文本框

    首先演示一个NumberFormatter的例子,在这个例子中要求用户输入一个数字,单击按钮后将用户输入的数字乘2以后重新赋值给输入框.用户输入的数字必须大于0,小于100. package com. ...

  3. VB中的format格式化函数

    VB Format函数 Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强制返回为文本 - - - - - - - - - - - - - - - ...

  4. java格式化星期_在Java中使用SimpleDateFormat格式化星期几

    Java日期中使用E格式来格式化星期一,星期二,星期三等星期几.让我们使用它.//显示星期几 SimpleDateFormat simpleformat = new SimpleDateFormat( ...

  5. 中软国际入职java考核_中软国际技术人员入职试题2(Java)

    中软国际技术人员入职试题2(Java) Java 笔试试题 一.介绍JSP中常用的内部对象.(时间4分钟) 1 request 2 response 3 out 4 application 5 ses ...

  6. java底层原理书籍_阿里面试题:Java中this和super关键字的底层实现原理

    知道的越多,不知道的就越多,业余的像一棵小草! 编辑:业余草 来源:https://www.xttblog.com/?p=5028 B 站:业余草 最近一个粉丝加我说,接到了阿里的面试,问问我阿里会面 ...

  7. java面试题27 java中下面哪些是Object类的方法()

    java面试题27 java中下面哪些是Object类的方法() A notify() B notifyAll() C sleep() D wait() 蒙蔽树上蒙蔽果,蒙蔽树下你和我.遇到这种题,我 ...

  8. java char 计算_经典Java面试题之Java中Char类型的运算

    经典Java面试题之Java中Char类型的运算 char在java中称为"字符型",占2个字节.本文是百分网小编搜索整理的关于经典Java面试题之Java中Char类型的运算,有 ...

  9. 在Java中调用Python,java面试题,java初级笔试题

    写在最前面,我总结出了很多互联网公司的面试题及答案,并整理成了文档,以及各种学习的进阶学习资料,免费分享给大家.扫码加微信好友进[程序员面试学习交流群],免费领取.也欢迎各位一起在群里探讨技术. 写在 ...

最新文章

  1. 设计模式C#实现(十五)——命令模式
  2. SpringBoot 之 MVC
  3. linux卸载netbeans,如何清除NetBeans中的缓存
  4. 通过SSH克隆远程仓库(GitLab)到本地
  5. html:(24):内联式css和嵌入式css
  6. elementUI table 表格表头居中 颜色、内容居左
  7. jupyter notebook使用基础及其快捷键,包括对文档操作、cell操作、快捷键、markdown
  8. 《微表情心理学》总结
  9. 【Java课设】学生信息管理系统简易版(文件IO代替数据库)
  10. directshow虚拟摄像头
  11. 汽车智造(一)| 移动机器人(AGV AMR)如何赋能汽车行业制造升级
  12. 蛙蛙推荐:蛙蛙浏览器
  13. ubuntu安装pinta(图片编辑器)
  14. 【U8】登录账套显示“账套XXX年度XXXX是以前版本的数据,请使用系统管理升级”
  15. 2019年全国大学生电子设计大学(D 题)简易电路特性测试仪(2)基础部分电路与代码
  16. 双通道连续波多普勒雷达测速模型 - Matlab仿真
  17. 让小屏幕kindlePaperWhite2支持PDF
  18. MAC 关闭office软件自动更新提示 (Microsoft AutoUpdate)
  19. Buyou:让你在iPad上轻松购物
  20. LeetCode-Python-1258. 近义词句子 ( DFS)

热门文章

  1. 【Arduino】入门篇——火焰报警器
  2. 华纳云:香港机房基础网络架构
  3. 如何将CentOS Stream退回为CentOS 8.5
  4. SyncE和1588的关系
  5. mysql 恢复sql文件
  6. 电网视频监控系统国网B接口中注册的接口流程GB281181国标流媒体服务平台
  7. (初级)数据分析学习总结(EXCEL)
  8. centos7进系统图形化一直转圈或命令行提示starting switch root 处理方法
  9. Pandas50个高级高频操作
  10. 迁移学习篇之如何迁移经典CNN网络-附迁移学习Alexnet,VGG,Googlenet,Resnet详细代码注释和方法-pytorch