溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何使用java8的格式化Date

發(fā)布時間:2021-10-12 16:31:17 來源:億速云 閱讀:125 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要講解了“如何使用java8的格式化Date”,文中的講解內(nèi)容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“如何使用java8的格式化Date”吧!

SimpleDateFormat 線程不安全

眾所周知 SimpleDateFormat 線程不安全,不少朋友被其坑過。

public class ExampleClass {

	private static final Pattern dateCreateP = Pattern.compile("Дата подачи:\\s*(.+)");
	private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd.MM.yyyy");

	public static void main(String[] args) {
		ExecutorService executor = Executors.newFixedThreadPool(100);
		while (true) {
			executor.submit(new Runnable() {
				@Override
				public void run() {
					workConcurrently();
				}
			});
		}
	}

	public static void workConcurrently() {
		Matcher matcher = dateCreateP.matcher("Дата подачи: 19:30:55 03.05.2015");
		Timestamp startAdvDate = null;
		try {
			if (matcher.find()) {
				String dateCreate = matcher.group(1);
				startAdvDate = new Timestamp(sdf.parse(dateCreate).getTime());
			}
		} catch (Throwable th) {
			th.printStackTrace();
		}
		System.out.print("OK ");
	}
}

And result :

OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK java.lang.NumberFormatException: For input string: ".201519E.2015192E2"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at java.text.DigitList.getDouble(DigitList.java:169)
at java.text.DecimalFormat.parse(DecimalFormat.java:2056)
at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1869)
at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
at java.text.DateFormat.parse(DateFormat.java:364)
at com.nonscalper.webscraper.processor.av.ExampleClass.workConcurrently(ExampleClass.java:37)
at com.nonscalper.webscraper.processor.av.ExampleClass$1.run(ExampleClass.java:25)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

解決方案

  1. 每次 new (實例化) SimpleDateFormat。

  2. 利用 ThreadLocal 確保每個線程都可以得到單獨的一個 SimpleDateFormat。

public class DateUtil {
	private static final ThreadLocal<SimpleDateFormat> local = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

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

	public static Date parse(String dateStr) throws ParseException {
		return local.get().parse(dateStr);
	}
}
  1. commons-lang3 中的 FastDateFormat。

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>${commons-lang3-version}</version>
</dependency>

性能比拼

性能咋樣,jmh 來一把,源碼見:https://github.com/lets-mica/mica-jmh

# JMH version: 1.21
# VM version: JDK 1.8.0_221, Java HotSpot(TM) 64-Bit Server VM, 25.221-b11

Benchmark             Mode  Cnt       Score       Error  Units
newSimpleDateFormat  thrpt    5  114072.841 ±   989.135  ops/s
threadLocal          thrpt    5  348207.331 ± 46014.175  ops/s
fastDateFormat       thrpt    5  434391.553 ±  7799.593  ops/s

結(jié)果:fastDateFormat 得分最高。當然你覺得這樣就完了?

利用 Instant + DateTimeFormatter

mica 1.2.1 中我們利用 Instant 來中轉(zhuǎn) Date 使用 DateTimeFormatter 格式化。

public static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());

public String format(Date date) {
	return DATETIME_FORMATTER.format(date.toInstant());
}

注意:DateTimeFormatter 格式化 Instant 需要指定時區(qū)。

jdk 8 壓測結(jié)果

# JMH version: 1.21
# VM version: JDK 1.8.0_221, Java HotSpot(TM) 64-Bit Server VM, 25.221-b11

Benchmark         Mode  Cnt       Score      Error  Units
fastDateFormat   thrpt    5  417338.980  56543.104  ops/s
toInstantFormat  thrpt    5  371028.709  72059.917  ops/s

jdk 11 壓測結(jié)果

# JMH version: 1.21
# VM version: JDK 11.0.4, OpenJDK 64-Bit Server VM, 11.0.4+10-b304.69

Benchmark         Mode  Cnt       Score      Error  Units
fastDateFormat   thrpt    5  384637.138   7402.690  ops/s
toInstantFormat  thrpt    5  487482.436  12490.986  ops/s

感謝各位的閱讀,以上就是“如何使用java8的格式化Date”的內(nèi)容了,經(jīng)過本文的學習后,相信大家對如何使用java8的格式化Date這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI