首页 > 解决方案 > 尝试将日期转换为本地时区时出错

问题描述

我正在使用简单的日期格式将两种不同的日期格式转换为本地时区和单一格式,然后比较它们是否相等。我的代码无法转换代码中给出的起始日期。

当我在“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

标签: javadatesimpledateformat

解决方案


推荐阅读