我想将java.util.Date
对象转换为String
Java中的对象.
格式是 2010-05-30 22:15:52
请告诉代码示例为什么SimpleDateFormat不是线程安全的.这堂课有什么问题? SimpleDateFormat的格式功能有问题吗?请给出一个在课堂上演示此错误的代码.
FastDateFormat是线程安全的.为什么?b/w SimpleDateFormat和FastDateFormat有什么区别?
请用解释此问题的代码解释一下?
我可以通过这种方式将a转换java.util.Date
为java.time.Instant
(Java 8及更高版本):
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 8);
cal.set(Calendar.MINUTE, 30);
Date startTime = cal.getTime();
Instant i = startTime.toInstant();
Run Code Online (Sandbox Code Playgroud)
有人能告诉我有关特定日期和时间格式的即时转换吗?即2015-06-02 8:30:00
我已经通过api但找不到满意的答案.
在各种Android项目中,我使用以下静态函数来解析日期等1900-12-31
.当然,这个功能应该是确定性的 - 但事实证明它不是.为什么?
通常,它会将日期解析2010-10-30
为例如Date
保存该值的正确实例.但我注意到,当我同时IntentService
运行并解析某些日期时,此函数会解析与上面相同的日期1983-01-20
,这是在其中解析的日期之一IntentService
.怎么会发生这种情况?
public static Date dateFromString(String dateStr) {
SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
SimpleDateFormat mDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault());
Date dateOut = null;
try {
if (dateStr != null) {
if (dateStr.length() == 7) {
if (dateStr.startsWith("--")) {
dateStr = "0000"+dateStr.substring(1);
}
}
else if (dateStr.length() == 6) {
if (dateStr.startsWith("-")) {
dateStr = "0000"+dateStr;
}
}
else if (dateStr.length() == 5) {
dateStr = …
Run Code Online (Sandbox Code Playgroud) SonarQube 5.5(带sonar-java-plugin-3.13.1.jar
插件)报告此代码的问题:
public class TimeA {
public static final SimpleDateFormat DATE_FORMATTER;
static {
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
DATE_FORMATTER=df;
}
}
Run Code Online (Sandbox Code Playgroud)
错误消息是 Make "DATE_FORMATTER" an instance variable.
我怎样才能避免这个SonarQube问题?
我班上有以下代码
private static final SimpleDateFormat SDF_ISO_DATE = new SimpleDateFormat("yyyy-MM-dd");
private static final SimpleDateFormat SDF_ISO_TIME = new SimpleDateFormat("HH:mm:ss");
public static String getTimeStampAsString(final long time) {
TimeZone tz = TimeZone.getTimeZone("UTC");
SDF_ISO_DATE.setTimeZone(tz);
SDF_ISO_TIME.setTimeZone(tz);
return SDF_ISO_DATE.format(
new Date(time)) + " " + SDF_ISO_TIME.format(new Date(time)
);
}
Run Code Online (Sandbox Code Playgroud)
在我的多线程应用程序中,以下方法将来会返回日期,即使对于当前日期,静态方法或变量是否对此负责?
编辑:
我有以下代码来重现和证明答案中提到的内容,但仍然无法.可以帮助我同样的一些人.
public static void main(String[] args) throws InterruptedException, ExecutionException {
Callable<String> task = new Callable<String>(){
public String call() throws Exception {
return DateUtil.getTimeStampAsString(1524567870569L);
}
};
//pool with 50 threads
ExecutorService exec = Executors.newFixedThreadPool(50);
List<Future<String>> results = …
Run Code Online (Sandbox Code Playgroud)