gpt4 book ai didi

Java日期转换

转载 作者:行者123 更新时间:2023-12-01 08:10:19 25 4
gpt4 key购买 nike

在下面的代码中输入:

Enter Date: 3/2/2011

输出:

Entered Date is February 3, 2011
Entered Month is 02

问题是,当我输入这个日期3/14/2012时,日期格式函数会自动将月份更改为12+2(二月)。如果我输入 13/15/2011,它会将月份更改为 3(12+3)

它应该在 14 上给出错误,“月份无效”

package lesson4;

import java.util.*;

import java.text.*;
public class ConvertDate {
static String Month;
static String fulldate;
static int month;
static int[] montharray={1,2,3,4,5,6,7,8,9,10,11,12};
public static void main(String[] args){


Scanner sc = new Scanner(System.in);
System.out.print("Enter Date: ");
String ind = sc.nextLine();
//Date now = new Date();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat f = new SimpleDateFormat("dd");
SimpleDateFormat m = new SimpleDateFormat("MM");

Date d = null;
Date e=null;
Date g=null;


try {
d=df.parse(ind);
e=df.parse(ind);
g=df.parse(ind);
DateFormat df3 = DateFormat.getDateInstance(DateFormat.LONG);


fulldate = df3.format(d);
Month=m.format(g);
month =Integer.parseInt(Month);

String date =f.format(e);
} catch (ParseException e1) {
// TODO Auto-generated catch block



e1.printStackTrace();
}





System.out.println("The entered date is: " + fulldate);
System.out.println("The entered month is: " + Month);

}
}

最佳答案

对于每个 DateFormat 实例,您需要使用 false 参数调用 setLenient:

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setLenient(false);
DateFormat f = new SimpleDateFormat("dd");
f.setLenient(false);
DateFormat m = new SimpleDateFormat("MM");
m.setLenient(false);

来自DateFormat#setLenient(boolean)文档:

With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.

关于Java日期转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18011004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com