How to make Date language independent?

I have a db that stores dates in a format OleDateTimein the GMT time zone. I implemented a class extending Datein java to represent this in a classic date format. But my class depends on the locale (I am in GMT + 2). Therefore, it converts the date to db as date - 2 hours. How can I convert the date correctly? I want my class to be language independent, always using GMT time zone. Actually the question arises:

class MyOleDateTime extends Date {

    static {
        Locale.setDefault(WhatGoesHere?)
    }

    // ... some constructors
    // ... some methods
}
+3
source share
5 answers

, Calendar, . , , TimeZone.setDefault(TimeZone.getTimeZone("UTC")); . user.timezone Java.

( ), , , GMT/UTC ( ), - .

, Date . getTime() , 1 1970 00:00:00 ( ) UTC. - , Calendar, . . Date, ?

+7

, Java Date . 01-01-1970 00:00:00 UTC.

, , , Date String DateFormat. DateFormat, , Date.

DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss Z");
df.setTimeZone(TimeZone.getTimeZone("UTC"));

String text = df.format(date);  // text will contain date represented in UTC
+6

, GMT. GMT (: UTC).

Date, , , getDay() - . . - - UTC! , - .

+2

Calendar :

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
                                    locale);
0

Here is a snippet that I used to calculate the GMT offset from the instance Calendarand formatted it. I appreciate all the help I received from this site, it's nice to contribute. Hope this helps someone. Enjoy it.

Calendar calInst = Calendar.getInstance();

//calculate the offset to keep calendar instance GMT
int gmtOffsetMilli = calInst.get(Calendar.ZONE_OFFSET);
long gmtOffsetHr = TimeUnit.HOURS.convert(gmtOffsetMilli, TimeUnit.MILLISECONDS);

calInst = Calendar.getInstance(TimeZone.getTimeZone("GMT " + gmtOffsetHr));
0
source

Source: https://habr.com/ru/post/1742427/


All Articles