SimpleDateFormat来做Date到String的类型转换,建议使用Apache commons-lang中的FastDateFormat。
因为JDK里自带的SimpleDateFormat存在线程不安全问题。
直接贴上代码,参数里是long型的时间戳
/**
* Created by huanghong on 2016/11/4.
*/
@Service
public class DateFormatService {
public static final TimeZone UTC = TimeZone.getTimeZone("UTC");
public static final FastDateFormat ISO_DATETIME_TIME_ZONE_FORMAT_WITH_MILLIS = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", UTC);
public String dateFormat(long timestamp) {
return ISO_DATETIME_TIME_ZONE_FORMAT_WITH_MILLIS.format(timestamp);
}
}
UTC是国际时区。
通过FastDateFormat直接转化
导入三个包
import org.apache.commons.lang.time.FastDateFormat; import org.springframework.stereotype.Service; import java.util.TimeZone;
简单的小工具类。