Sha*_*mar 9 java timezone date date-conversion
我已编写此代码以将当前系统日期和时间转换为其他时区.我没有收到任何错误,但我没有按预期得到我的输出.就像我在特定时间执行我的程序..我的输出是::
印度当前时间是::Fri Feb 24 16:09:23 IST 2012
:: Central Standard Time中的日期和时间::Sat Feb 25 03:39:23 IST 2012
根据CST时区的实际时间是::
Friday, 24 February 4:39:16 a.m(GMT - 6:00)
Run Code Online (Sandbox Code Playgroud)
所以有一些时间差距.我不知道为什么会这样.任何帮助将不胜感激..代码是::
package MyPackage;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class Temp2 {
public static void main(String[] args) {
try {
Calendar currentdate = Calendar.getInstance();
String strdate = null;
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
strdate = formatter.format(currentdate.getTime());
TimeZone obj = TimeZone.getTimeZone("CST");
formatter.setTimeZone(obj);
//System.out.println(strdate);
//System.out.println(formatter.parse(strdate));
Date theResult = formatter.parse(strdate);
System.out.println("The current time in India is :: " +currentdate.getTime());
System.out.println("The date and time in :: "+ obj.getDisplayName() + "is ::" + theResult);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Nis*_*ant 20
它在网上.可以用Google搜索.无论如何,这里有一个版本(从这里无耻地挑选和修改):
Calendar calendar = Calendar.getInstance();
TimeZone fromTimeZone = calendar.getTimeZone();
TimeZone toTimeZone = TimeZone.getTimeZone("CST");
calendar.setTimeZone(fromTimeZone);
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
if (fromTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}
System.out.println(calendar.getTime());
Run Code Online (Sandbox Code Playgroud)
你的错误是打电话parse而不是format.
您调用parse从字符串解析日期,但在您的情况下,您有一个日期,需要使用正确的时区格式化它.
替换你的代码
Calendar currentdate = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
TimeZone obj = TimeZone.getTimeZone("CST");
formatter.setTimeZone(obj);
System.out.println("Local:: " +currentdate.getTime());
System.out.println("CST:: "+ formatter.format(currentdate.getTime()));
Run Code Online (Sandbox Code Playgroud)
我希望你能得到你期望的输出.
SimpleDateFormat#setTimezone()是答案。一个带有ETC时区的格式化程序用于解析,另一个UTC用于生成输出字符串:
DateFormat dfNy = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
dfNy.setTimeZone(TimeZone.getTimeZone("EST"));
DateFormat dfUtc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
dfUtc.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return dfUtc.format(dfNy.parse(input));
} catch (ParseException e) {
return null; // invalid input
}
Run Code Online (Sandbox Code Playgroud)