Java中日期转换的 parse() 和 format() 方法设计缺陷的补救方法

首先是在上生产之前代码安全监测问题所得出,日期转换的parse() 和 format() 方法设计存在缺陷,以下补救过程。

监测图:

问题所在:

Abstract:

java.text.Format 中的 parse() 和 format() 方法包含一个可导致用户看到其他用户数据的设计缺陷。

Explanation:

java.text.Format 中的 parse() 和 format() 方法包含一个可导致用户看到其他用户数据的 race condition。

例 1: 以下代码显示了此设计缺陷如何暴露自己。

public class Common {
private static SimpleDateFormat dateFormat;
...
public String format(Date date) {
return dateFormat.format(date);
}
...
final OtherClass dateFormatAccess=new OtherClass();
...
public void function_running_in_thread1(){
System.out.println("Time in thread 1 should be 12/31/69 4:00 PM, found: "+ dateFormatAccess.format(new Date(0)));
}
public void function_running_in_thread2(){
System.out.println("Time in thread 2 should be around 12/29/09 6:26 AM, found: "+ dateFormatAccess.format(new
Date(System.currentTimeMillis())));
}}

       尽管此代码可在单一用户环境中正常运行,但如果两个线程同时运行此代码,则会生成以下输出内容:

Time in thread 1 should be 12/31/69 4:00 PM, found: 12/31/69 4:00 PM

Time in thread 2 should be around 12/29/09 6:26 AM, found:12/31/69 4:00 PM

在这种情况下,第一个线程中的数据显示在了第二个线程的输出中,原因是实施的 format() 中存在 race condition。

Recommendations:

    调用类 java.text.Format 中的 parse() 和 format() 时,请使用同步来防例 2: 以下代码显示了使用同步构造更正例 1 中代码的两种方式。

public class Common {
private static SimpleDateFormat dateFormat;
...
public synchronized String format1(Date date) {
return dateFormat.format(date);
Fortify Security Report
Copyright 2010 Fortify Software Inc. Page 6 of 
12
}
public String format2(Date date) {
synchronized(dateFormat)
{
return dateFormat.format(date);
}}}

注意:

总结的方法代码:

package com.yinxin.control;

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

public class Test {
	private static SimpleDateFormat dateFormat;
	 
	public synchronized static String formatAll(Date date,String timeType) {
		dateFormat=new SimpleDateFormat(timeType);
		return dateFormat.format(date);
	}
	
	public synchronized static Date formatDate(String date,String timeType) throws ParseException{
	dateFormat=new SimpleDateFormat(timeType);
	 return dateFormat.parse(date);
	}
	
   public static void main(String[] args) {
	   //测试
	   String strDate=formatAll(new Date(),"yyyyMMdd");
	   System.out.println("Date类型转换成字符串型为["+strDate+"]");
	   Date date=null;
	try {
		date = formatDate("2019-07-17 18:02:25","yyyy-MM-dd HH:mm:SS");
	} catch (ParseException e) {
		e.printStackTrace();
	}
	   System.out.println("字符串的日期格式转换为Date类型之后为["+date+"]");
   }
}

效果图:

注意:在字符串转换为日期的时候,两边格式一定要相同,不然会报异常的

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

醉梦洛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值