ESTで日付を印刷する方法を提案してください。
public Date convertToEST(Date date)
{
// some code here
}
ISTで日付を渡すと、メソッドはESTでその日付を返す必要があります。
次のものが必要です
Date date = new Date();
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
// Set the formatter to use a different timezone
formatter.setTimeZone(TimeZone.getTimeZone("EST"));
// Prints the date in the EST timezone
System.out.println(formatter.format(date));
メソッドをオブジェクトに戻すには、Date
以下に示すように必要です。
public static Date convertToEST(Date date) throws ParseException {
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("EST"));
return formatter.parse((formatter.format(date)));
}
Javadoc- DateFormat.format
、DateFormat.parse
「メソッドはESTでその日付を返す必要がある」という考えは間違っています。日付は、1970年1月1日00:00:00GMTからのミリ秒の保持者にすぎません。タイムゾーンとは何の関係もありません。
Javaでのタイムゾーンの変更
public class TimeZoneSample {
public static void main(String[] args) throws ParseException {
// I am in IST time Zone (Its ID is Asia/Calcutta or ITS)
System.out.println(TimeZone.getDefault());
// I get Indian Time printed
System.out.println(new Date());
System.out.println("-------------------");
// I am setting the time zone to China
TimeZone.setDefault(TimeZone.getTimeZone("CTT"));
// Now my default time zone is in China
System.out.println(TimeZone.getDefault());
// I get Chian Time printed
System.out.println(new Date());
System.out.println("-------------------");
// I am setting the time zone to EST
TimeZone.setDefault(TimeZone.getTimeZone("EST"));
// Now my default time zone is in EST
System.out.println(TimeZone.getDefault());
// I get Eastern Time printed
System.out.println(new Date());
}
}
コンソール出力
sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null]
Wed Dec 26 10:22:25 IST 2012
-------------------
sun.util.calendar.ZoneInfo[id="CTT",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null]
Wed Dec 26 12:52:25 CST 2012
-------------------
sun.util.calendar.ZoneInfo[id="EST",offset=-18000000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
Tue Dec 25 23:52:25 EST 2012
DateFormat requiredDateFormat = new SimpleDateFormat("hh:mm a zzz, EEE MMMM dd,yyyy");
requiredDateFormat.setTimeZone(TimeZone.getTimeZone("US/Eastern"));
String date = requiredDateFormat.format(new Date());
System.out.println(date);
コンソール出力:2018年2月13日火曜日、東部標準時午前6時25分