我想要一个以下面的方式工作的代码 显示8-10个城市的时间,其中应自动处理DST。
For example : Melbourne observes DST, a API using which I can fetch the current time based on location without any hardcode done for DST calculation.
目前正在运行的代码基于硬编码值。它选择系统时间转换为GMT,然后根据位置添加/减去偏移量。
然后根据日期计算DST并适当添加。
但是我想使用一些API来删除硬编码的值,我试图使用下面的代码。
The below code giving time for IST/GMT, but when I put AEST/AEDT it doesnt give the correct time.
public class DateFormatter {
public static String formatDateToString(Date date, String format,
String timeZone) {
// null check
if (date == null) return null;
// create SimpleDateFormat object with input format
SimpleDateFormat sdf = new SimpleDateFormat(format);
// default system timezone if passed null or empty
if (timeZone == null || "".equalsIgnoreCase(timeZone.trim())) {
timeZone = Calendar.getInstance().getTimeZone().getID();
}
// set timezone to SimpleDateFormat
sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
// return Date in required format with timezone as String
return sdf.format(date);
}
public static void main(String[] args) {
//Test formatDateToString method
Date date = new Date();
System.out.println("Default Date:"+date.toString());
System.out.println("System Date: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", null));
System.out.println("System Date in PST: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", "PST"));
System.out.println("System Date in IST: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", "IST"));
System.out.println("System Date in GMT: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", "GMT"));
System.out.println("System Date in CT: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", "BDT"));
}
}
答案 0 :(得分:0)
import java.time.LocalTime;
import java.time.ZoneId;
public class Main {
public static void main(String... args) {
ZoneId zone2 = ZoneId.of("America/Santiago");
LocalTime now2 = LocalTime.now(zone2);
System.out.println(now2);
}
}
Use the below link to know the timezones
答案 1 :(得分:0)
package com.java.test;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import javax.swing.text.ZoneView;
public class TestJavaCode {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
Calendar cal = GregorianCalendar.getInstance();
TimeZone tzone = cal.getTimeZone();
tzone.useDaylightTime();
System.out.println("Timezone:"+tzone.getDisplayName());
TimeZone tzone1 = TimeZone.getTimeZone("Canada/Central");
TimeZoneIDProvide.getTimeZoneID(TimeZoneID.US_EASTERN).getTimeZone();
Calendar cal1 = new GregorianCalendar(tzone1);
cal1.setTimeInMillis(cal.getTimeInMillis());
System.out.println("Time in US Hour: "+cal1.get(Calendar.HOUR));
System.out.println("Time in US Min: "+cal1.get(Calendar.MINUTE));
System.out.println("Time in US Sec: "+cal1.get(Calendar.SECOND));
}
catch(Exception e)
{
System.out.println("Exception caught:"+e);
}
}
}