Skip to content

Instantly share code, notes, and snippets.

@jyeary
Last active August 29, 2015 14:24
Show Gist options
  • Save jyeary/4ee59e7ad41a6e573baa to your computer and use it in GitHub Desktop.
Save jyeary/4ee59e7ad41a6e573baa to your computer and use it in GitHub Desktop.
ISO8601 DateFormat
/*
* Copyright 2015 Blue Lotus Software, LLC.
*
* 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.
*/
package com.bluelotussoftware.jsf.utils;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* A collection of utilities to handle common date conversions.
*
* @author John Yeary <[email protected]>
* @version 1.0
*/
public final class DateUtils {
private static final ThreadLocal<DateFormat> iso8601DateFormatter = new ThreadLocal<DateFormat>() {
@Override
public DateFormat get() {
return super.get();
}
@Override
protected DateFormat initialValue() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormat;
}
@Override
public void remove() {
super.remove();
}
@Override
public void set(DateFormat value) {
super.set(value);
}
};
/**
* <p>
* Convert a {@link Date} to an ISO 8601 combined date and time string.</p>
* <p>
* <strong>Note:</strong> This method is thread-safe since it uses a
* {@link ThreadLocal} version of the {@link DateFormat} class.
*
* @param date The {@link Date} to evaluate and convert.
* @return {@code String} with format "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
*/
public static String getISO8601Date(final Date date) {
String formattedDate = iso8601DateFormatter.get().format(date);
iso8601DateFormatter.remove();
return formattedDate;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment