java - 尝试将日期转换为本地时区时出错
问题描述
我正在使用简单的日期格式将两种不同的日期格式转换为本地时区和单一格式,然后比较它们是否相等。我的代码无法转换代码中给出的起始日期。
当我在“2019 年 9 月 11 日 - 凌晨 1:00 BRT/BRDT” AM 中提供日期时,我的代码运行良好,但它在下午时间失败。示例日期为“2019 年 9 月 11 日 - BRT/BRDT 下午 1:00”。
公共类 DateSample {
public static void main(String[] args) throws ParseException {
DateSample obj = new DateSample ();
String str= obj.dateCompare(
"MMM dd,yyyy - HH:mm aaa z",
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
"Sep 11, 2019 - 1:00 pm BRT/BRDT",
"2019-09-11T13:00:00.000-03:00"
);
System.out.println(str);
}
String dateCompare(String fromDateFormat, String toDateFormat,String fromdate, String todate)throws ParseException{
String CheckFormat = "MMMMM yyyy HH:mm:ss.SSSZ";
String dateStringFrom;
String dateStringTo;
Date DF = new Date();
Date DT = new Date();
int flagtodate=0;
int flagfromdate=0;
try
{
//DateFormatdf = DateFormat.getDateInstance(DateFormat.SHORT);
DateFormat FromDF = new SimpleDateFormat(fromDateFormat);
FromDF.setLenient(false);
Date FromDate = FromDF.parse(fromdate);
dateStringFrom = new SimpleDateFormat(CheckFormat).format(FromDate);
DateFormat FromDF1 = new SimpleDateFormat(CheckFormat);
DF=FromDF1.parse(dateStringFrom);
System.out.println("From Date is ok = " + dateStringFrom);
}
catch (ParseException e)
{
flagfromdate = 1;
}
catch (IllegalArgumentException e)
{
flagfromdate = 1;
}
try
{
//DateFormatdf = DateFormat.getDateInstance(DateFormat.SHORT);
DateFormat ToDF = new SimpleDateFormat(toDateFormat);
ToDF.setLenient(false);
Date ToDate = ToDF.parse(todate);
dateStringTo = new SimpleDateFormat(CheckFormat).format(ToDate);
DateFormat ToDF1 = new SimpleDateFormat(CheckFormat);
DT=ToDF1.parse(dateStringTo);
System.out.println("To Date is ok = " + dateStringTo);
}
catch (ParseException e)
{
flagtodate=1;
}
catch (IllegalArgumentException e)
{
flagtodate=1;
}
if(flagfromdate == 0 &&flagtodate==0)
{
if(DF.equals(DT))
{
// if the date is same
return "FromDate and ToDate are same";
}
else if(DF.before(DT))
{
//if the from date is before the to date
return "FromDate is less than ToDate";
}
else
{
// if the date from is after the to date
return "FromDate is greater than the ToDate";
}
}
return "Error";
}
}
下面提到的是失败情况下控制台的输出:
迄今为止还可以 = 2019 年 9 月 21:30:00.000+0530
错误
成功案例输出:
从日期确定 = 2019 年 9 月 09:30:00.000+0530
迄今为止还可以 = 2019 年 9 月 21:30:00.000+0530
FromDate 小于 ToDate
解决方案
推荐阅读
- loops - 有没有办法在 DB2 中添加一个 while 循环?
- javascript - 如何使用对象的括号表示法和属性名称的字符串向对象添加属性?
- python - 带单引号且不带转义字符的 JSON 对象
- node.js - MySQL 查询不会超过承诺链中的某个点
- regex - 301 重定向到 URL 中带有 # 的域
- scikit-learn - 在 svm.scv() 中同时使用“class_weight”和“c”参数会发生什么?
- postgresql - PostgreSQL Generate_Series() 插入未完成
- c++ - 调试 curl 未处理的异常
- c# - 对项目源进行列表插入时,组合框项目未更新
- java - 如何检查超过和低于某些预定限制的值