Java技能点之SimpleDateFormat进行日期格式化问题

2023-07-04 0 3,491

目录

SimpleDateFormat进行日期格式化

1.为啥要用SimpleDateFormat

众所周知,Java中的日期类是Date,然后日期默认的输出样式很奇怪哦,是这样子的:

package org.maoge.common;
import java.util.Date;
public class SimpleDateFormatDemo {
	public static void main(String[] args) {
		//默认输出格式
		Date date=new Date();
		System.out.println(date);//Fri Oct 27 16:56:37 CST 2017
	}
}

真的好像说,这是什么鬼啊,神经病啊,老板要是发现你在前端把日期显示成这样子,非要…觉得你很有个性不可。

OK,所以就很需要将日期以一种我们想要的格式显示出来

另外,有时候我们需要指定一个日期,所以也需要将字符串类型转换为Date类型,我们往往会以为是这样子的:

Java技能点之SimpleDateFormat进行日期格式化问题

首先我们就注意到了new Date()方法被划上了删除线,这个就表示该方法在定义的时候被@Deprecated注解注解过了,意思是该方法过期了不建议使用了可能有问题了,反正咱知道这个方法最好不用就是了。而且,确实也报错了,所以我们也需要一种将字符串转换为日期的方法

SimpleDateFormat就是为这两种需要诞生滴,类库嘛,就是前人搭棚好乘凉,而且都是牛逼的前人。

2.日期格式化显示

首先要记住一些标记:(注意大小写)

  • 年yyyy
  • 月MM
  • 日dd
  • 时HH
  • 分mm
  • 秒ss
  • 毫秒SS

然后直接看例子:

package org.maoge.common;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo {
	public static void main(String[] args) {
		//默认输出格式
		Date date=new Date();
		System.out.println(date);//Fri Oct 27 16:56:37 CST 2017
		//日期格式化显示,首先定义格式
		SimpleDateFormat sdf1=new SimpleDateFormat(\"yyyyMMdd\");//显示20171027格式
		SimpleDateFormat sdf2=new SimpleDateFormat(\"yyyy-MM-dd\");//显示2017-10-27格式
		SimpleDateFormat sdf3=new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");//显示2017-10-27 10:00:00格式
		SimpleDateFormat sdf4=new SimpleDateFormat(\"yyyy年MM月dd日HH时mm分ss秒\");//显示2017年10月27日10时00分00秒格式
		//将格式应用于日期
		System.out.println(sdf1.format(date));//20171027
		System.out.println(sdf2.format(date));//2017-10-27
		System.out.println(sdf3.format(date));//2017-10-27 17:11:13
		System.out.println(sdf4.format(date));//2017年10月27日17时11分13秒
	}
}

3.将字符串转换为对应日期

注意,因为可能定义的格式和实际字符串提供的格式不符合,所以会抛出异常

package org.maoge.common;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo {
	public static void main(String[] args) {
		//首先定义格式
		SimpleDateFormat sdf1=new SimpleDateFormat(\"yyyyMMdd\");
		SimpleDateFormat sdf2=new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");
		//按格式进行转换
		String strDate1=\"20151010\";//符合sdf1格式
		String strDate2=\"20171027 10:00:00\";//不符合格式
		try {
			Date date1=sdf1.parse(strDate1);
			System.out.println(date1);//正常输出Sat Oct 10 00:00:00 CST 2015
			Date date2=sdf2.parse(strDate2);//报错java.text.ParseException: Unparseable date: \"20171027 10:00:00\"
			System.out.println(date2);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}

SimpleDateFormat的使用及其注意事项

SimpleDateFormat API 简介

/**
 * SimpleDateFormat
 * 一个与语言环境相关的格式化日期和分析日期的工具类。
 * 利用该类可以将日期转换成文本,或者将文本转换成日期。
 * 
 * 在使用SimpleDateFormat时需要指定一个需要的格式(pattern)来格式日期(Date).
 * 在此请注意几个字母大小写的差异:
 * 
 * 大写的H为24小时制表示一天中的小时数(0-23)
 * 小写的h为12小时制表示一天中的小时数(1-12)
 * 
 * 大写的M表示年中的月份 
 * 小写的m表示小时中的分钟数 
 * 
 * 大写的S表示毫秒数
 * 小写的s表示秒数
 * 
 * 所以最常用的24小时制的具体日期的pattern为:
 * yyyy-MM-dd HH:mm:ss
 * 
 * 
 * SimpleDateFormat中format()方法小结:
 * 1 format()方法的作用是将日期(Date)转换为文本
 * 2 format()方法的输入参数是一个Date
 * 
 * 
 * SimpleDateFormat中parse()方法小结:
 * 1 parse()方法的作用是将文本转换为日期(Date)
 * 2 parse()方法的输入参数是一个文本,比如String
*/

1. 将日期转换为文本

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;


Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.getDefault());
String time = simpleDateFormat.format(date);

System.out.println(\"----> 格式化后的日期为: \"+time);
System.out.println(\"----------------------------------\");

输出:

System.out: ----> 格式化后的日期为: 2019-05-23 22:28:01
System.out: ----------------------------------

2. 将文本转换为日期

/**
  * 请注意:
  * 
  * 文本的格式应该与 SimpleDateFormat 中的 pattern 保持一致,否则导致异常
  * 比如:
  * 2008年08月18日 20:07:33   对应于yyyy年MM月dd日 HH:mm:ss
  * 2008-08-18 20:07:33           对应于yyyy-MM-dd HH:mm:ss
*/
private void test2() {
  try {
        String day = \"2008年08月18日 20:07:33\";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\"yyyy年MM月dd日 HH:mm:ss\", Locale.getDefault());
        Date date = simpleDateFormat.parse(day);
        System.out.println(\"----> 格式化后的日期为: \"+date);

        day = \"2008-08-18 20:07:33\";
        simpleDateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.getDefault());
        date = simpleDateFormat.parse(day);
        System.out.println(\"----> 格式化后的日期为: \"+date);

        day = \"20131227085009\";
        simpleDateFormat = new SimpleDateFormat(\"yyyyMMddHHmmss\", Locale.getDefault());
        date = simpleDateFormat.parse(day);
        simpleDateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.getDefault());
        String time = simpleDateFormat.format(date);
        System.out.println(\"----> 时间文本为: \"+time);

        System.out.println(\"----------------------------------\");
    } catch (Exception e) {
        System.out.println(\"----> Exception: \"+e.toString());
    }
}

输出:

System.out: ----> 格式化后的日期为: Mon Aug 18 20:07:33 GMT+08:00 2008
System.out: ----> 格式化后的日期为: Mon Aug 18 20:07:33 GMT+08:00 2008
System.out: ----> 时间文本为: 2013-12-27 08:50:09

3. 将时间戳转换成时间

long timeStamp=System.currentTimeMillis();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.getDefault());
Date date = new Date(timeStamp);
String time = simpleDateFormat.format(date);

System.out.println(\"----> 将时间戳转换为字符串: \"+time);
System.out.println(\"----------------------------------\");

输出:

System.out: ----> 将时间戳转换为字符串: 2019-05-23 22:36:27

4. 将时间转换成时间戳

long timeStamp = System.currentTimeMillis();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.getDefault());
Date date = new Date(timeStamp);
String time = simpleDateFormat.format(date);

System.out.println(\"----> 当前时间戳为: \"+timeStamp+\" ,其字符串为:\"+time);

Date parsedDate = simpleDateFormat.parse(time);
long ts = parsedDate.getTime();

System.out.println(\"----> 将字符串转换为时间戳: \"+ts);
System.out.println(\"----------------------------------\");

输出:

----> 当前时间戳为: 1558622317494 ,其字符串为:2019-05-23 22:38:37
----> 将字符串转换为时间戳: 1558622317000

5. java时间戳与unix时间戳的关系

/**
 * java中生成的时间戳精确到毫秒,但unix中精确到秒
 * 所以两者相差1000倍
 */

long javaTimeStamp = System.currentTimeMillis();
long unixTimeStamp = javaTimeStamp/1000;
System.out.println(\"----> java时间戳: \" + javaTimeStamp+\", unix时间戳:\" + unixTimeStamp);
System.out.println(\"----------------------------------\");

输出:

System.out: ----> java时间戳: 1558622474893 ,unix时间戳:1558622474

6. 计算两个时间的差值

private String time1=\"2016-01-02 00:00:00\";
private String time2=\"2013-09-21 00:00:00\";


private void getTimeDifference(String time1,String time2) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.getDefault());
try {

   Date date1 = simpleDateFormat.parse(time1);
   Date date2 = simpleDateFormat.parse(time2);
   long difference = date1.getTime() - date2.getTime();
   long days = difference / (1000 * 60 * 60 * 24);
   System.out.println(\"----> 两个时间相距:\"+days+\"天\");
   
} catch (Exception e) {
    System.out.println(\"----> Exception=\"+e.toString());
}
    System.out.println(\"----------------------------------\");
}

输出:

System.out: ----> 两个时间相距:833天

7. 比较两个时间的大小

private void compareTime(String time1, String time2) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.getDefault());
    Calendar calendar1 = java.util.Calendar.getInstance();
    Calendar calendar2 = java.util.Calendar.getInstance();
    try {
        calendar1.setTime(dateFormat.parse(time1));
        calendar2.setTime(dateFormat.parse(time2));
    } catch (java.text.ParseException e) {
        System.out.println(\"----> Exception=\" + e.toString());
    }
    int result = calendar1.compareTo(calendar2);
    if (result == 0){
        System.out.println(\"----> time1等于time2\");
    }else if (result < 0) {
        System.out.println(\"----> time1小于time2\");
    }else {
        System.out.println(\"----> time1大于time2\");
    }
}

输出:

System.out: ----> time1大于time2

8. 线程安全的使用方法

ThreadLocal

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ConcurrentDateUtil {

    private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");
        }
    };

    public static Date parse(String dateStr) throws ParseException {
        return threadLocal.get().parse(dateStr);
    }

    public static String format(Date date) {
        return threadLocal.get().format(date);
    }
}

使用 ThreadLocal, 也是将共享变量变为独享,线程独享肯定能比方法独享在并发环境中能减少不少创建对象的开销。如果对性能要求比较高的情况下,一般推荐使用这种方法。

Java 8 中的解决办法

Java 8 提供了新的日期时间 API,其中包括用于日期时间格式化的 DateTimeFormatter,它与 SimpleDateFormat 最大的区别在于:DateTimeFormatter 是线程安全的,而 SimpleDateFormat 并不是线程安全。

  • 解析日期
String dateStr= \"2018年06月20日\";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"yyyy年MM月dd日\");   
LocalDate date= LocalDate.parse(dateStr, formatter);
  • 日期转换为字符串
LocalDateTime now = LocalDateTime.now();  
DateTimeFormatter format = DateTimeFormatter.ofPattern(\"yyyy年MM月dd日 hh:mm a\");
String nowStr = now.format(format);

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

资源下载此资源下载价格为1小猪币,终身VIP免费,请先
由于本站资源来源于互联网,以研究交流为目的,所有仅供大家参考、学习,不存在任何商业目的与商业用途,如资源存在BUG以及其他任何问题,请自行解决,本站不提供技术服务! 由于资源为虚拟可复制性,下载后不予退积分和退款,谢谢您的支持!如遇到失效或错误的下载链接请联系客服QQ:442469558

:本文采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可, 转载请附上原文出处链接。
1、本站提供的源码不保证资源的完整性以及安全性,不附带任何技术服务!
2、本站提供的模板、软件工具等其他资源,均不包含技术服务,请大家谅解!
3、本站提供的资源仅供下载者参考学习,请勿用于任何商业用途,请24小时内删除!
4、如需商用,请购买正版,由于未及时购买正版发生的侵权行为,与本站无关。
5、本站部分资源存放于百度网盘或其他网盘中,请提前注册好百度网盘账号,下载安装百度网盘客户端或其他网盘客户端进行下载;
6、本站部分资源文件是经压缩后的,请下载后安装解压软件,推荐使用WinRAR和7-Zip解压软件。
7、如果本站提供的资源侵犯到了您的权益,请邮件联系: 442469558@qq.com 进行处理!

猪小侠源码-最新源码下载平台 Java教程 Java技能点之SimpleDateFormat进行日期格式化问题 http://www.20zxx.cn/774433/xuexijiaocheng/javajc.html

猪小侠源码,优质资源分享网

常见问题
  • 本站所有资源版权均属于原作者所有,均只能用于参考学习,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,建议提前注册好百度网盘账号,使用百度网盘客户端下载
查看详情

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务