使用SimpleDateFormat必须注意的问题

王朝other·作者佚名  2008-05-31
宽屏版  字体: |||超大  

在使用SimpleDateFormat的经常会有一些错误的用法,例如如下方式:

Word-BREAK: break-all; PADDING-TOP: 4px; BORDER-BOTTOM: #cccccc 1px solid; BACKGROUND-COLOR: #eeeeee"

public class TestDateFormat
{

PRivate SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

public void method1()
{

sdf.format(new Date());

}

public void method2()
{

sdf.format(new Date());

}

)

为了渐少new 的次数而把SimpleDateFormat做成成员或者静态成员,但这样的做法是隐含着错误的,是不

安全的。如下给出证实:

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.HashMap;

import java.util.Map;

public class TestDateFormat
{

private SimpleDateFormat sdf ;

public static void main(String[] args)
{

SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");

Date date1 = new Date();

Date date2 = new Date(date1.getTime()+1000*60*60*24);

System.out.println(date1);

System.out.println(date2);

Thread thread1 = new Thread(new Thread1(sdf,date1));

thread1.start();

Thread thread2 = new Thread(new Thread2(sdf,date2));

thread2.start();

}

}

class Thread1 implements Runnable
{

private SimpleDateFormat sdf;

private Date date;

public Thread1(SimpleDateFormat sdf,Date date)
{

this.sdf = sdf;

this.date = date;

}

public void run()
{

for(;;)
{

String strDate = sdf.format(date);

if("2007-02-27".equals(strDate))
{

System.err.println("Error: date1="+strDate);

System.exit(0);

}

}

}

}

class Thread2 implements Runnable
{

private SimpleDateFormat sdf;

private Date date;

public Thread2(SimpleDateFormat sdf,Date date)
{

this.sdf = sdf;

this.date = date;

}

public void run()
{

for(;;)
{

String strDate = sdf.format(date);

if("2007-02-26".equals(strDate))
{

System.err.println("Error: date1="+strDate);

System.exit(0);

}

}

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有