Java ZonedDateTime Format format(ZonedDateTime zonedDateTime)

Here you can find the source of format(ZonedDateTime zonedDateTime)

Description

format

License

Apache License

Declaration

public static String format(ZonedDateTime zonedDateTime) 

Method Source Code

//package com.java2s;
/*/*from   www. ja va 2 s.c om*/
 * Copyright 2017 StreamSets Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;

import java.util.List;
import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;

public class Main {
    private static final Map<String, String[]> TEMPLATES = new ConcurrentHashMap<>();
    private static final String TOKEN = "{}";

    public static String format(String template, Object... args) {
        String[] templateArr = TEMPLATES.get(template);
        if (templateArr == null) {
            // we may have a race condition here but the end result is idempotent
            templateArr = prepareTemplate(template);
            TEMPLATES.put(template, templateArr);
        }
        StringBuilder sb = new StringBuilder(template.length() * 2);
        for (int i = 0; i < templateArr.length; i++) {
            sb.append(templateArr[i]);
            if (args != null && i < templateArr.length - 1) {
                sb.append((i < args.length) ? args[i] : TOKEN);
            }
        }
        return sb.toString();
    }

    public static String format(ZonedDateTime zonedDateTime) {
        return zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
    }

    static String[] prepareTemplate(String template) {
        List<String> list = new ArrayList<>();
        int pos = 0;
        int nextToken = template.indexOf(TOKEN, pos);
        while (nextToken > -1 && pos < template.length()) {
            list.add(template.substring(pos, nextToken));
            pos = nextToken + TOKEN.length();
            nextToken = template.indexOf(TOKEN, pos);
        }
        list.add(template.substring(pos));
        return list.toArray(new String[list.size()]);
    }
}

Related

  1. format(ZonedDateTime zdt, DateTimeFormatter dtf)
  2. formatDate(ZonedDateTime dateTime)
  3. formatDate(ZonedDateTime dt)
  4. formatDate_ddMMYYYYHHmmss(ZonedDateTime now)
  5. formatDateAsShortDateLocalTime(ZonedDateTime moonDate, ZoneId tz)