首页 > 编程知识 正文

java date格式(javadate)

时间:2023-05-05 02:28:03 阅读:76097 作者:1156

正如他所说,OPP对他问题的解决方案令人怀疑。 这个代码仍然显示了对时间显示的混乱。 为了消除这一混乱,避免代码导致错误,请考虑对他进行的扩展。

公共静态void _ test date formatting (

simpledateformatsdfgmt1=newsimpledateformat (yyyy.mm.ddhh 3360 mm : ss );

sdfg mt1. settime zone (time zone.gettime zone ) ) GMT );

simpledateformatsdfgmt2=newsimpledateformat (yyyy.mm.ddhh 3360 mm : ssz );

sdfg mt2.settime zone (time zone.gettime zone ) ) GMT );

simpledateformatsdflocal1=newsimpledateformat (yyyy.mm.ddhh : mm : ss );

simpledateformatsdflocal2=newsimpledateformat (yyyy.mm.ddhh : mm : ssz );

try {

日期d=new date (;

String s1=d.toString (;

stringS2=SDFlocal1.format(d;

//store S3 or S4 in数据库。

stringS3=sdfgmt1.format(d;

stringS4=sdfgmt2.format(d;

//Retrieve s3 or s4 from database,using LOCAL sdf。

stringS5=SDFlocal1.parse(S3 ).toString );

//exception strings6=SDF local2. parse (S3 ).toString );

stringS7=SDFlocal1.parse(S4 ).toString );

stringS8=SDFlocal2.parse(S4 ).toString );

//Retrieve s3 from database,using GMT sdf。

//notethatthisisthesamesdfthatcreateds 3。

dateD2=sdfgmt1.parse(S3;

String s9=d2.toString (;

stringS10=sdfgmt1.format(D2;

stringS11=SDFlocal2.format(D2;

}catch(exceptione ) {

e .打印堆栈跟踪(;

}

}

在调试器中检查值:

S1 ' monsep 0706336011336053 EDT 2015 ' (id=831698113128 )

S2 ' 2015.09.0706336011336053 ' (id=831698114048 ) )。

S3 ' 2015.09.0710336011336053 ' (id=831698114968 ) ) ) ) ) ) ) ) ) )。

S4 ' 2015.09.0710336011336053 GMT 00336000 ' (id=831698116112 ) ) ) ) ) ) ) ) ) )。

S5 ' monsep 0710336011336053 EDT 2015 ' (id=831698116944 ) ) ) ) ) ) ) ) ) )。

S6--已提交,gave parse exception

S7 ' monsep 0710336011336053 EDT 2015 ' (id=831698118680 ) ) ) ) ) ) ) ) ) )。

S8 ' monsep 0706336011336053 EDT 2015 ' (id=831698119584 )

S9 ' monsep 0706336011336053 EDT 2015 ' (id=831698120392 )

S10 ' 2015.09.0710336011336053 ' (id=831698121312 ) )。

S11 ' 2015.09.0706336011336053 EDT ' (id=83169812256 ) ) ) ) ) ) ) ) ) )。

sdf2和sdfLocal2包含时区,您可以在其中查看实际情况。 s1和s2位于EDT区域的06:11:53中。 s3和s4等于格林威治标准时间10:11:53-原始EDT时间。 假设使用GMT将s3或s4存储在一致的数据库中,则可以从世界上的任何地方获取时间,而无需存储不同的时区。

分析S5GMT时间,但将其视为本地时间。 因此,虽然被称为“10:11336053”(格林威治标准时间),但当地时间被认为是10336011336053。 不好。

s7分析GMT时间,但会忽略字符串中的GMT,因此将其视为本地时间。

s8起作用,因为本地区域设置解析器(包括字符串中的GMT )使用它将一个时区转换为另一个时区。

现在,假设您不想保存区域,想分析s3,但想将其显示为本地时间。 答案将使用与存储时区相同的时区进行解决。 因此,请使用与创建时区相同的sdfGMT1。 s9、s10和s11都是原始时间的表示。 那些都是“正确的”。 即,d2==d1。 而且,这只是你如何显示它的问题。 要显示数据库中存储的内容-GMT时间-,必须使用GMT sdf进行格式设置。 这是s10。

因此,如果您不想在字符串中显式保存“GMT”,而想以GMT格式显示,这是最终的解决方案。

公共静态void _ test date formatting (

simpledateformatsdfgmt1=newsimpledateformat (yyyy.mm.ddhh 3360 mm : ss );

sdfg mt1. settime zone (time zone.gettime zone ) ) GMT );

try {

日期d=new date (;

stringS3=sdfgmt1.format(d;

//Store s3 in DB。

//.

//Retrieve s3 from database,using GMT sdf。

dateD2=sdfgmt1.parse(S3;

stringS10=sdfgmt1.format(D2;

}catch(exceptione ) {

e .打印堆栈跟踪(;

}

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。