Ser*_*Amo 49 java timezone jodatime
我的应用程序托管在伦敦服务器中.我在西班牙马德里.所以时区是-2小时.
如何获取我的时区的当前日期/时间.
Date curr_date = new Date(System.currentTimeMillis());
Run Code Online (Sandbox Code Playgroud)
例如
Date curr_date = new Date(System.currentTimeMillis("MAD_TIMEZONE"));
Run Code Online (Sandbox Code Playgroud)
DateTimeZone zone = DateTimeZone.forID("Europe/Madrid");
DateTime dt = new DateTime(zone);
int day = dt.getDayOfMonth();
int year = dt.getYear();
int month = dt.getMonthOfYear();
int hours = dt.getHourOfDay();
int minutes = dt.getMinuteOfHour();
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 89
Date
是始终基于UTC ...或时区中立的,这取决于你想如何看待它.甲Date
只表示在一个时间点; 它独立于时区,自Unix时代以来只有几毫秒.没有"本地实例"的概念Date
.使用Date
结合Calendar
和/或TimeZone.getDefault()
使用"本地"时区.使用TimeZone.getTimeZone("Europe/Madrid")
得到马德里时区.
...或者使用Joda Time,它可以让整个事情变得更加清晰,IMO.在Joda Time中,您将使用一个DateTime
值,该值是特定日历系统和时区中的即时时间.
在Java 8中你使用的java.time.ZonedDateTime
是Joda Time的Java 8等价物DateTime
.
Jes*_*per 52
正如Jon Skeet所说,java.util.Date
没有时区.一个Date
对象表示自1970年1月1日,上午12:00,UTC毫秒数.它不包含时区信息.
将Date对象格式化为字符串时(例如使用)SimpleDateFormat
,可以在DateFormat
对象上设置时区,以便知道要在哪个时区显示日期和时间:
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Use Madrid's time zone to format the date in
df.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
System.out.println("Date and time in Madrid: " + df.format(date));
Run Code Online (Sandbox Code Playgroud)
如果您想要运行程序的计算机的本地时区,请使用:
df.setTimeZone(TimeZone.getDefault());
Run Code Online (Sandbox Code Playgroud)
dfa*_*dfa 16
使用日历很简单:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Madrid"));
Date currentDate = calendar.getTime();
Run Code Online (Sandbox Code Playgroud)
使用Java 8和更高版本中内置的java.time类:
public static void main(String[] args) {
LocalDateTime localNow = LocalDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
System.out.println(localNow);
// Prints current time of given zone without zone information : 2016-04-28T15:41:17.611
ZonedDateTime zoneNow = ZonedDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
System.out.println(zoneNow);
// Prints current time of given zone with zone information : 2016-04-28T15:41:17.627+02:00[Europe/Madrid]
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
204246 次 |
最近记录: |