我有以下代码:
package com.company.customer;
import java.util.*;
import java.text.*;
import java.io.*;
public class DateSample {
private TimeZone GMT_TIMEZONE = TimeZone.getTimeZone("GMT");
private SimpleDateFormat sdfDate = new SimpleDateFormat();
private Date inputDate;
private String dateInString = "2015-07-15";
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
public void datePrint() {
sdfDate.setTimeZone(GMT_TIMEZONE);
sdfDate.applyPattern("EE-ddMMM");
try {
inputDate = formatter.parse(dateInString);
} catch (Exception e) {
System.out.println("populateTabDates: ParseException");
}
String formatResults = sdfDate.format(inputDate);
// Modify the return to cut down the weekday: Fri-20Aug => Fr-20Aug
formatResults = formatResults.substring(0, 2) + formatResults.substring(3);
System.out.println(formatResults);
}
}
Run Code Online (Sandbox Code Playgroud)
当我将PC设置为伦敦时区并将PC小时更改为8或9am时,会出现问题.然后,formatResults变量显示14而不是7月15日; 有什么想法吗?
您尚未设置时区formatter,因此无论系统默认时区是什么.
因此,您正在使用系统默认时区解析"2015-07-15".如果那是伦敦,那么您的解析日期是2015-07-15T00:00:00 + 01,即2015-07-14T23:00:00Z.当您使用UTC时区和日期部分格式化时,您将在7月14日到达.
基本上,将两个格式化程序放在同一时区,或者您应该期望一个解析/格式对来"移动"该值.(如果您还在解析和格式化时间,这将更容易看到.)
我还建议使用UTCUTC时区的名称而不是GMT; 后者可能会让一些人误以为它是英国时区,它在GMT和BST之间交替.