Java Date to String dateToRFC3339(Date d)

Here you can find the source of dateToRFC3339(Date d)

Description

Format dates as specified in rfc3339 (required for Atom dates)

License

Open Source License

Parameter

Parameter Description
d the Date to be formatted

Return

the formatted date

Declaration

public static String dateToRFC3339(Date d) 

Method Source Code

//package com.java2s;
/* (c) 2014 Open Source Geospatial Foundation - all rights reserved
 * (c) 2001 - 2013 OpenPlans/*w w w  . j a  v  a2s  . com*/
 * This code is licensed under the GPL 2.0 license, available at the root
 * application directory.
 */

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import java.util.TimeZone;

public class Main {
    /**
     * A date formatting object that does most of the formatting work for RFC3339.  Note that since 
     * Java's SimpleDateFormat does not provide all the facilities needed for RFC3339 there is still
     * some custom code to finish the job.
     */
    private static DateFormat rfc3339 = new SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm:ss");
    /**
     * A number formatting object to format the the timezone offset info in RFC3339 output.
     */
    private static NumberFormat doubleDigit = new DecimalFormat("00");

    /**
     * Format dates as specified in rfc3339 (required for Atom dates)
     * @param d the Date to be formatted
     * @return the formatted date
     */
    public static String dateToRFC3339(Date d) {
        StringBuilder result = new StringBuilder(rfc3339.format(d));
        Calendar cal = new GregorianCalendar();
        cal.setTime(d);
        cal.setTimeZone(TimeZone.getDefault());
        int offset_millis = cal.get(Calendar.ZONE_OFFSET)
                + cal.get(Calendar.DST_OFFSET);
        int offset_hours = Math.abs(offset_millis / (1000 * 60 * 60));
        int offset_minutes = Math.abs((offset_millis / (1000 * 60)) % 60);

        if (offset_millis == 0) {
            result.append("Z");
        } else {
            result.append((offset_millis > 0) ? "+" : "-")
                    .append(doubleDigit.format(offset_hours)).append(":")
                    .append(doubleDigit.format(offset_minutes));
        }

        return result.toString();
    }
}

Related

  1. dateToIso8601String(Date date)
  2. dateToISODate(Date date)
  3. dateToOracleDateString(Date date)
  4. dateToRelativeTime(Date date)
  5. dateToRFC1123(Date date)
  6. dateToStr(Date date)
  7. dateToStr(Date date)
  8. dateToStr(Date date)
  9. dateToStr(Date date)