Java Timestamp Format formatTimestamp(String dateStr, String granularity)

Here you can find the source of formatTimestamp(String dateStr, String granularity)

Description

format Timestamp

License

Apache License

Declaration

public static String formatTimestamp(String dateStr, String granularity) 

Method Source Code

//package com.java2s;
/*/*w  w  w . j  ava2 s. c o  m*/
 *
 * Copyright 2011, 2012, 2013 the University of New Mexico.
 *
 * This work was supported by National Science Foundation Cooperative
 * Agreements #DEB-0832652 and #DEB-0936498.
 *
 * 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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static String formatTimestamp(String dateStr, String granularity) {
        SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
        SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        String timestamp = null;

        try {
            if (dateStr == null) {

            } else if (dateStr.length() == 4) {
                Date yearDate = yearFormat.parse(dateStr);
                timestamp = iso8601Format.format(yearDate);
            } else if (dateStr.length() == 10) {
                Date yearMonthDayDate = yearMonthDayFormat.parse(dateStr);
                timestamp = iso8601Format.format(yearMonthDayDate);
            }

            // Append the granularity if it is specified
            if (timestamp != null && granularity != null) {
                timestamp = String.format("%s/%s", timestamp, granularity);
            }
        } catch (ParseException e) {
            // Can't parse this date string. Just return null.
        }

        return timestamp;
    }
}

Related

  1. formatTimestamp(long timestamp)
  2. formatTimestamp(long timestamp)
  3. formatTimestamp(long timestamp)
  4. formatTimestamp(long timestamp)
  5. formatTimestamp(long ts)
  6. formatTimestamp(Timestamp dataHora)
  7. formatTimeStamp(Timestamp t)
  8. formatTimestamp(Timestamp t, int type)
  9. formatTimestamp(Timestamp timestamp)