How to set time zone in Yaml date string?

I use org.yaml.snakeyaml.Yaml.

SimpleDateFormat uses the system time zone (UTC +6: 30).

I want yaml output like SimpleDateFormat.

public static void main(String[] args) throws Exception {
    String dateString = "2015-11-17 15:30:30"; 
    /*
        SimpleDateFormat will UTC +6:30 (Myanmar Timezone)
    */
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date sdfDate = format.parse(dateString);
    System.out.println("Date 1 " + format.format(sdfDate));

    /*
        Yaml will not use.
    */
    Yaml yaml = new Yaml();
    //yaml.setTimeZone(xxx) --> Is there way to set timezone?
    Date yamlDate = (Date) yaml.load(dateString);

    System.out.println("Date 2" + format.format(yamlDate));
}

Exit

Date 1 2015-11-17 15:30:30
Date 2 2015-11-17 22:00:30
+4
source share
3 answers

I am not sure if this is the best way to solve this problem.
Temporarily, I have to decide as shown below.

which calculates different times (for example: +6: 30) programmatically and adds to the date string.

Example Date Line: 2015-11-17 15:30:30 +6:30.

    String sdfSt = "2015-11-17 15:30:30";

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date sdfDate = format.parse(sdfSt);
    System.out.println("Date 1 " + format.format(sdfDate));

    Yaml yaml = new Yaml();
    String itmeDiff = "+6:30"; --> for my timezone
    Date yamlDate = (Date) yaml.load(sdfSt + itmeDiff);
    System.out.println("Date 2 " + format.format(yamlDate));

Exit

Date 1 2015-11-17 15:30:30
Date 2 2015-11-17 15:30:30
0
source

YAML , , ( .yml) UTC. , , .yml , snakeyaml, .

snakeyaml DumperOptions, :

DumperOptions options = new DumperOptions();
options.setTimeZone(TimeZone.getTimeZone("GMT+6:30"));
Yaml yaml = new Yaml(options);
0

My code works for this problem according to the code below:

TimeZone.getTimeZone("UTC");
Yaml yaml = new Yaml();
0
source

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


All Articles