Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Methods for generating ISO 8601 timestamps in Java/Android
package net.kristopherjohnson.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* Methods for dealing with timestamps
*/
public class TimestampUtils {
/**
* Return an ISO 8601 combined date and time string for current date/time
*
* @return String with format "yyyy-MM-dd'T'HH:mm:ss'Z'"
*/
public static String getISO8601StringForCurrentDate() {
Date now = new Date();
return getISO8601StringForDate(now);
}
/**
* Return an ISO 8601 combined date and time string for specified date/time
*
* @param date
* Date
* @return String with format "yyyy-MM-dd'T'HH:mm:ss'Z'"
*/
private static String getISO8601StringForDate(Date date) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormat.format(date);
}
/**
* Private constructor: class cannot be instantiated
*/
private TimestampUtils() {
}
}
@rwheadon

This comment has been minimized.

Copy link

rwheadon commented Dec 12, 2016

Thank you for this gist, it saved few minutes for sure

@ysoftware

This comment has been minimized.

Copy link

ysoftware commented Dec 26, 2016

Thanks!

@antalakas

This comment has been minimized.

Copy link

antalakas commented Jan 23, 2017

Thanks!

@omervk

This comment has been minimized.

Copy link

omervk commented Jun 5, 2017

Note: getISO8601StringForCurrentDate only returns correct results if your machine is configured to UTC.

@wavyxu

This comment has been minimized.

Copy link

wavyxu commented May 27, 2018

Thanks!

@lajtmaN

This comment has been minimized.

Copy link

lajtmaN commented Apr 1, 2019

Here is a more recent way to do this:
DateTimeFormatter.ISO_DATE_TIME.format(LocalDateTime.now())

@taimoorgit

This comment has been minimized.

Copy link

taimoorgit commented Jun 22, 2019

Thanks. For some reason all the stackoverflow solutions are sooo inefficient. Annoying!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.