Java Date Convert dateToUTC(Date d)

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

Description

Converts a Date object into a string in 'Zulu' format

License

Open Source License

Parameter

Parameter Description
d A <code>Date</code> object to be converted into a string in 'Zulu' format

Return

A string representing the date contained in the passed Date object in 'Zulu' format (e.g. yyyyMMDDThhmmssZ)

Declaration

public static String dateToUTC(Date d) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.Calendar;
import java.util.Date;

public class Main {
    /**//from  w ww .  j  a  v a2s  .  c  o  m
     * Converts a <code>Date</code> object into a string in 'Zulu' format
     *
     * @param d
     *            A <code>Date</code> object to be converted into a string in
     *            'Zulu' format
     * @return A string representing the date contained in the passed
     *         <code>Date</code> object in 'Zulu' format (e.g.
     *         yyyyMMDDThhmmssZ)
     */
    public static String dateToUTC(Date d) {
        StringBuffer date = new StringBuffer();
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);

        date.append(cal.get(Calendar.YEAR));

        date.append(printTwoDigits(cal.get(Calendar.MONTH) + 1)).append(printTwoDigits(cal.get(Calendar.DATE)))
                .append("T");

        date.append(printTwoDigits(cal.get(Calendar.HOUR_OF_DAY))).append(printTwoDigits(cal.get(Calendar.MINUTE)))
                .append(printTwoDigits(cal.get(Calendar.SECOND))).append("Z");

        return date.toString();
    }

    /**
     * Returns a string representation of number with at least 2 digits
     */
    private static String printTwoDigits(int number) {
        if (number > 9) {
            return String.valueOf(number);
        } else {
            return "0" + number;
        }
    }
}

Related

  1. dateToString(Date date)
  2. dateToString(Date date)
  3. dateToString(Date date)
  4. dateToString(final Date date)
  5. dateToUnixTimestamp(Date date)
  6. dateToXdsDateString(Date date, int format)
  7. dateToXmlDateTime(final Date date)