为什么通过仅设置一个TimeZone,SimpleDateFormat.format()和SimpleDateFormat.parse()会给出不同的时间? [英] Why SimpleDateFormat.format() and SimpleDateFormat.parse() are giving different time though setting only one TimeZone?

查看:35
本文介绍了为什么通过仅设置一个TimeZone,SimpleDateFormat.format()和SimpleDateFormat.parse()会给出不同的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 SimpleDateFormat 将时区设置为其他国家的时区. SimpleDateFormat.format()返回给定时区的正确当前时间,但是 SimpleDateFormat.parse()返回本地当前时间,我不知道为什么会这样.这是我的代码-

I am trying to set the Timezone to the different country's timezone with help of SimpleDateFormat. SimpleDateFormat.format() returns correct current time of the given Timezone, but SimpleDateFormat.parse() returns local current time, I dont know why this is happening. Here is the my code -

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
System.out.println("Time1 : " + dateFormat.format(new Date()));
System.out.println("Time2 : " + dateFormat.parse(dateFormat.format(new Date())));

输出为-

Time1 : 2013-01-17 21:01:55
Time2 : Fri Jan 18 10:30:55 IST 2013

Time1是"America/Los_Angeles"的输出,而Time2是本地(即"Asia/Calcutta")的输出.

我只想要UTC Seconds格式的给定时区的当前时间(即,自1970年1月1日以来的Seconds).

I just want the current time of given Timezone in UTC Seconds format (ie Seconds since Jan 1, 1970).

为什么SimpleDateFormat.format()和SimpleDateFormat.parse()尽管只设置了一个时区,却给出了不同的时间?

请帮助我.

推荐答案

Parse (解析),您可以命令编译器理解特定格式的给定日期.它了解并保持其自己的格式,并准备提供您想要的任何格式!

with Parse, you command the compiler to understand the given date in specific format. It understands and keep it in its own format and ready to give whatever format you want!

您将得到一个输出,这是您输入日期已成功解析的信号.您无法控制变量存储的date的格式.

You are getting a output, which is a signal that you input date is parsed successfully. You dont have a control over the format of the date , that the variable is storing.

使用格式,您可以将日期转换为任何所需的格式.

using format, you can convert the date to any desired format.

简单地解析->阅读(我可以以任何方式阅读并以我想要的任何方式存储)格式->写(我会以您想要的格式给您)

Simply Parse -> Reading ( I may read it in whatever manner and store in whatever manner I want) Format -> Write ( I will give you in the format you wanted )

这篇关于为什么通过仅设置一个TimeZone,SimpleDateFormat.format()和SimpleDateFormat.parse()会给出不同的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆