Java日期转换

标签 java date

在下面的代码中 输入:

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/

相关文章:

Java : Random setSeed

.net - 如何确保日期有效?

sql-server - 在SQL Server中查找一周的第一天,第二天等

java - 如何检查两个日期是否在一个时间段(间隔)之间?

JavaScript 显示服务器上存储为 UTC 的日期的正确日期

java - 如何部署 OSGi 应用程序和依赖项?

Java 8 流条件检查

java - 我想在 PHP 中集成 Aadhaar 卡身份验证。我尝试使用此代码进行 API 访问,但无法得到任何响应

java - 导入日期模式数据并忽略java中的其他字符串

java - 将Spring Boot集成到独立的现有Spring Jar中