This question already has answers here:
Changing YYYY/MM/DD -> MM/DD/YYYY java
(2 answers)
Closed 6 years ago.
I am inputting a specific date (dd/MM/yyyy) , while displaying it the Output is something else.
import java.text.*;
import java.io.*;
import java.util.*;
class InvalidUsernameException extends Exception //Class InvalidUsernameException
{
InvalidUsernameException(String s)
{
super(s);
}
}
///////////////////////////////////////////////////////////////////////////////////////////
class InvalidPasswordException extends Exception //Class InvalidPasswordException
{
InvalidPasswordException(String s)
{
super(s);
}
}
///////////////////////////////////////////////////////////////////////////////////////////
class InvalidDateException extends Exception //Class InvalidPasswordException
{
InvalidDateException(String s)
{
super(s);
}
}
///////////////////////////////////////////////////////////////////////////////////////////
class EmailIdb1 //Class Email Id b1
{
String username, password;
int domainid;
Date dt;
EmailIdb1()
{
username = "";
domainid = 0;
password = "";
dt = new Date();
}
EmailIdb1(String u, String pwd, int did, int d, int m, int y)
{
username = u;
domainid = did;
password = pwd;
dt = new Date(y,m,d); // I think There is a problem
SimpleDateFormat formater = new SimpleDateFormat ("yyyy/MM/dd"); //Or there can be a problem
try{
if((username.equals("User")))
{
throw new InvalidUsernameException("Invalid Username");
}
else if((password.equals("123")))
{
throw new InvalidPasswordException("Invalid Password");
}
else{
System.out.println("\nSuccesfully Login on Date : "+formater.format(dt));
}
}
catch(Exception e)
{
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////
class EmailId //Class Email Id
{
public static void main(String args[])
{
int d,m,y,did;
String usn,pwd;
EmailIdb1 eml;
try{
usn = args[0];
pwd = args[1];
did = Integer.parseInt(args[2]);
d = Integer.parseInt(args[3]);
m = Integer.parseInt(args[4]);
y = Integer.parseInt(args[5]);
switch(m)
{
case 2: if(d==29 && y%4 == 0)
{
eml = new EmailIdb1(usn,pwd,did,d,m,y);
}
else if(d<=28 && d>=1)
{
eml = new EmailIdb1(usn,pwd,did,d,m,y);
}
else{
throw new InvalidDateException("Wrong Date.");
}
break;
case 1: case 3: case 5: case 7: case 8: case 10:
case 12: if(d>=1 && d<=31)
{
eml = new EmailIdb1(usn,pwd,did,d,m,y);
}
else
{
throw new InvalidDateException("Invalid Date");
}
break;
case 4: case 6: case 9:
case 11: if(d>=1 && d<=30)
{
eml = new EmailIdb1(usn,pwd,did,d,m,y);
}
else
{
throw new InvalidDateException("Invalid Date");
}
break;
default : throw new InvalidDateException("Invalid Date");
}
}
catch(InvalidDateException ed)
{
System.out.println(ed);
}
}
}
Me and my two friends have similar kind of problem. Don't know why This is Happening. My teacher also couldn't find what's the problem
The Output Should be
Successfully Login on Date : 1994/05/04
As the Input Is
Successfully Login on Date : 3894/06/04
First of all
new Date(int year, int month, int date)
is deprecated - you shouldn't be using it
Second of all, according to the javadoc:
/**
* Allocates a <code>Date</code> object and initializes it so that
* it represents midnight, local time, at the beginning of the day
* specified by the <code>year</code>, <code>month</code>, and
* <code>date</code> arguments.
*
* #param year the year minus 1900.
* #param month the month between 0-11.
* #param date the day of the month between 1-31.
* #see java.util.Calendar
* #deprecated As of JDK version 1.1,
* replaced by <code>Calendar.set(year + 1900, month, date)</code>
* or <code>GregorianCalendar(year + 1900, month, date)</code>.
*/
So if you pass as a year 1994, you will get Date with year "3894". If you want to get "1994", you should pass 94 as a year.
And months are represented as int from range 0-11, so if you pass 5, it is formatted as "06" in your case, because 5 represents June and not May.
Related
I have jdk java version "1.8.0_45", i am using joda time api (joda-time-2.7.jar)
By using Joda time api i am getting a wrong date.
By using Jdk 8 hijri date api i am getting a correct date.
I have a requirement to convert a gregorian date to hijri date using java api.
My sample test class is as follows:
import org.joda.time.*;
import org.joda.time.chrono.*;
import java.time.*;
import java.time.chrono.HijrahChronology;
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception {
DateTime dtISO = new DateTime();
System.out.println("dtISO = "+dtISO);
DateTime dtIslamic = dtISO.withChronology(IslamicChronology.getInstance(DateTimeZone.UTC ));
System.out.println(dtIslamic.getYear()+"-" +dtIslamic.getMonthOfYear()+ "-"+ dtIslamic.getDayOfMonth());
java.time.chrono.HijrahDate hijradate = java.time.chrono.HijrahDate.now();
System.out.println("hijradate "+hijradate);
}
}
Output of this class is
C:\>java Test
dtISO = 2015-05-24T09:44:51.704+04:00
1436-8-5
hijradate Hijrah-umalqura AH 1436-08-06
Can you please tell me joda api is correct one or wrong one?
My production server has JDK1.6 i cannot upgrade it to 1.8 as of now, so kindly let me know your suggestions to get a proper hijri date .... Awaiting for your reply....
The difference you are seeing between JodaTime and JDK8 is because they use different implementations of the Hijri Calendar. There are multiple algorithms to compute (approximate) a Hijri date.
Jdk8's HijrahChoronology uses an implementation of Umm-AlQura calendar which closely matches the official Hijri calendar in Saudi Arabia as defined in http://www.ummulqura.org.sa/.
JodaTime IslamicChronology has different implementations which you can select from using its factory methods see http://joda-time.sourceforge.net/apidocs/org/joda/time/chrono/IslamicChronology.html
So it really depends on system audience. If you are in Saudi Arabia or any country which relies on UmmAlQura calendar stick with the JDK8's implementation.
i found this code on http://junaedhalim.blogspot.com/2010/01/hijri-calendar-in-java-using-kuwaiti.html hopefully it help you
import java.util.Calendar;
import java.util.Date;
/**
*
* #author junaed
*/
public class HijriCalendar
{
private int[] userDateG;
private int[] userDateH;
private WaqtMidlet midlet;
private Calendar cal;
private int currentHijriDate;
private int currentHijriMonth;
private int currentHijriYear;
public static final String[] HIJRI_MONTHS =
{
"Muharram", "Safar", "Rabi' al-awwal", "Rabi' al-thani", "Jumada al-awwal",
"Jumada al-thani", "Rajab", "Sha'aban", "Ramadan", "Shawwal", "Dhu al-Qi'dah", "Dhu al-Hijjah"
};
public static final int[] BASE_DATE_G =
{
18, 11, 2009, 0, 0
};
public static final int[] BASE_DATE_H =
{
1, 0, 1431, 0, 0
};
public HijriCalendar(WaqtMidlet midlet)
{
this.midlet = midlet;
cal = Calendar.getInstance();
Date date = new Date();
cal.setTime(date);
}
private void updateDefinedTime()
{
String uTimeH = midlet.getRmsManager().getString(ApplicationConstants.RMS_HIJRI_DATE);
// String uTimeH = "";
if (uTimeH == null || uTimeH.equalsIgnoreCase(""))
{
userDateG = ApplicationConstants.BASE_DATE_G;
userDateH = ApplicationConstants.BASE_DATE_H;
}
else
{
System.out.println("uTimeH = " + uTimeH);
int date = Integer.parseInt(uTimeH.substring(0, uTimeH.indexOf(';')));
String rest = uTimeH.substring(uTimeH.indexOf(';') + 1);
int month = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
rest = rest.substring(rest.indexOf(';') + 1);
int year = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
rest = rest.substring(rest.indexOf(';') + 1);
int hour = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
rest = rest.substring(rest.indexOf(';') + 1);
int minute = Integer.parseInt(rest);
userDateH = new int[]
{
date, month, year, hour, minute
};
// String uTimeG = "";
String uTimeG = midlet.getRmsManager().getString(ApplicationConstants.RMS_GREGORIAN_DATE);
System.out.println("uTimeG = " + uTimeG);
date = Integer.parseInt(uTimeG.substring(0, uTimeG.indexOf(';')));
rest = uTimeG.substring(uTimeG.indexOf(';') + 1);
month = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
rest = rest.substring(rest.indexOf(';') + 1);
year = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
userDateG = new int[]
{
date, month, year, hour, minute
};
}
cal.set(Calendar.HOUR_OF_DAY, userDateG[3]);
cal.set(Calendar.MINUTE, userDateG[4]);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.DATE, userDateG[0]);
cal.set(Calendar.MONTH, userDateG[1]);
cal.set(Calendar.YEAR, userDateG[2]);
currentHijriDate = userDateH[0];
currentHijriMonth = userDateH[1];
currentHijriYear = userDateH[2];
}
private boolean isALeapYear(int year)
{
int modValue = year % 30;
switch (modValue)
{
case 2:
return true;
case 5:
return true;
case 7:
return true;
case 10:
return true;
case 13:
return true;
case 15:
return true;
case 18:
return true;
case 21:
return true;
case 24:
return true;
case 26:
return true;
case 29:
return true;
}
return false;
}
private int getDaysInThisYear(int year)
{
if (isALeapYear(year))
{
return 355;
}
return 354;
}
public int getDaysInThisMonth(int month, int year)
{
if (month % 2 != 0)
{
return 30;
}
else
{
if (month == 12)
{
if (isALeapYear(year))
{
return 30;
}
}
return 29;
}
}
private void addOneDayToCurrentDate()
{
currentHijriDate++;
if(currentHijriDate >= 29)
{
int daysInCurrentMonth = getDaysInThisMonth(currentHijriMonth, currentHijriYear);
if( currentHijriDate > daysInCurrentMonth)
{
currentHijriDate = 1;
currentHijriMonth++;
if(currentHijriMonth > 11)
{
currentHijriMonth = 1;
currentHijriYear++;
}
}
}
}
private void addDays(long days)
{
for(long i = 0; i< days; i++)
{
addOneDayToCurrentDate();
}
}
public String getCurrentDateStr()
{
updateDefinedTime();
Date date = new Date();
// int currentTime = calendar.get(Calendar.HOUR_OF_DAY);
long diff = date.getTime() - cal.getTime().getTime();
long days = diff / (1000 * 86400);
addDays(days);
String ret = currentHijriYear + " "+HIJRI_MONTHS[currentHijriMonth] + ", " + currentHijriDate;
return ret;
// return midlet.getRmsManager().getString(ApplicationConstants.RMS_HIJRI_DATE);
}
}
Try using ICU4J. Its Calendar classes do not extend java.util.Calendar, but they do properly deal with Hijri dates (and many other calendar systems). I was able to get what I believe are correct results using its IslamicCalendar class, using Java 1.6.0_31:
import java.util.Date;
import java.util.Locale;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.IslamicCalendar;
public class HijriDate {
public static void main(String[] args) {
java.util.Calendar gregorianCal =
java.util.Calendar.getInstance(Locale.US);
System.out.printf("%tF%n", gregorianCal);
Date date = gregorianCal.getTime();
Calendar cal = new IslamicCalendar();
cal.setTime(date);
System.out.printf("%02d-%02d-%02d%n",
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH) + 1,
cal.get(Calendar.DAY_OF_MONTH));
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have to modify my class so that it passes JUnit test cases. It seems like everything should be working fine but it keeps failing. It is giving me a java.lang.AssertionError.
Here is my class
package dayofweek;
/**
* Method to find out what day of the week a certain date was
*
* Output determines what day of the week this certain date was
*
*/
public class DayOfWeek {
private int myMonth = -1, myDayOfMonth = -1, myYear= -1, myAdjustment= -1, numericDayOfWeek= -1, remainderSeven= -1;
private static final int NO_VALUE = -1;
/**
* #param what the date was
*/
public DayOfWeek(int month, int dayOfMonth, int year){
myMonth = month;
myDayOfMonth = dayOfMonth;
myYear = year;
remainderSeven = 0;
if(myMonth==1){
myAdjustment = 1;
if(myYear%4==0){
myAdjustment=0;
}
}
if(myMonth==2){
myAdjustment = 4;
if(myYear%4==0){
myAdjustment=3;
}
}
if(myMonth==3){
myAdjustment = 4;
}
if(myMonth==4){
myAdjustment = 0;
}
if(myMonth==5){
myAdjustment = 2;
}
if(myMonth==6){
myAdjustment = 5;
}
if(myMonth==7){
myAdjustment = 0;
}
if(myMonth==8){
myAdjustment = 3;
}
if(myMonth==9){
myAdjustment = 6;
}
if(myMonth==10){
myAdjustment = 1;
}
if(myMonth==11){
myAdjustment = 4;
}
if(myMonth==12){
myAdjustment = 6;
}
int fourDivides = myYear / 4;
numericDayOfWeek = myAdjustment + myDayOfMonth + (myYear-1900) + fourDivides;
remainderSeven = numericDayOfWeek % 7;
}
/**
* #return the month in a string
*/
public String getMonthString(){
String[] arrayOfMonths = new String[12];
arrayOfMonths[0] = "January";
arrayOfMonths[1] = "February";
arrayOfMonths[2] = "March";
arrayOfMonths[3] = "April";
arrayOfMonths[4] = "May";
arrayOfMonths[5] = "June";
arrayOfMonths[6] = "July";
arrayOfMonths[7] = "August";
arrayOfMonths[8] = "September";
arrayOfMonths[9] = "October";
arrayOfMonths[10] = "November";
arrayOfMonths[11] = "December";
if (this.myMonth > 0 && this.myMonth <=12){
return arrayOfMonths[this.myMonth-1];
}
else{
return null;
}
}
/**
* #return what day of the month it was
*/
public int getDayOfMonth(){
if(myDayOfMonth != NO_VALUE){
return myDayOfMonth;
}
else{
return NO_VALUE;
}
}
/**
* #return what year it was
*/
public int getYear(){
if(myYear != NO_VALUE){
return myYear;
}
else{
return NO_VALUE;
}
}
/**
* #return the numeric day of the week
*/
public int getNumericDayOfWeek(){
return remainderSeven;
}
/**
* returns what day of the week it was
*/
public String getDayOfWeek(){
String[] arrayOfDays = new String[7];
arrayOfDays[0] = "Saturday";
arrayOfDays[1] = "Sunday";
arrayOfDays[2] = "Monday";
arrayOfDays[3] = "Tuesday";
arrayOfDays[4] = "Wednesday";
arrayOfDays[5] = "Thursday";
arrayOfDays[6] = "Friday";
if( myMonth != NO_VALUE && myDayOfMonth != NO_VALUE && myYear != NO_VALUE){
return arrayOfDays[remainderSeven];
}
else{
return null;
}
}
/**
* #return the month in an int
*/
public int getMonth(){
if(myMonth != NO_VALUE){
return myMonth;
}
else return NO_VALUE;
}
}
Here is the JUnit test class
package dayofweektesting;
import dayofweek.DayOfWeek;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Test cases for "Day of week" lab assuming requirements set
* at top of DayOfWeek class
*
* Test valid leap years
*
*
*/
public class TestValidLeapYears {
/**
* Test valid 2/29/XXXX dates
*/
#Test
public void firstValidLeapYear() {
DayOfWeek dow = new DayOfWeek(2, 29, 1904);
assertTrue(dow.getDayOfWeek().compareTo("Monday") == 0);
assertTrue(dow.getNumericDayOfWeek() == 2);
}
#Test
public void secondValidLeapYear() {
DayOfWeek dow = new DayOfWeek(2, 29, 1908);
assertTrue(dow.getDayOfWeek().compareTo("Saturday") == 0);
assertTrue(dow.getNumericDayOfWeek() == 0);
}
#Test
public void thirdValidLeapYear() {
DayOfWeek dow = new DayOfWeek(2, 29, 1912);
assertTrue(dow.getDayOfWeek().compareTo("Thursday") == 0);
assertTrue(dow.getNumericDayOfWeek() == 5);
}
#Test
public void fourthValidLeapYear() {
DayOfWeek dow = new DayOfWeek(2, 29, 1916);
assertTrue(dow.getDayOfWeek().compareTo("Tuesday") == 0);
assertTrue(dow.getNumericDayOfWeek() == 3);
}
/**
* Test boundary dates of2/28/XXXX and 3/1/XXXX for valid leap years
*/
#Test
public void firstValidLeapYearBoundaries() {
DayOfWeek dow = new DayOfWeek(2, 28, 1904);
assertTrue(dow.getDayOfWeek().compareTo("Sunday") == 0);
assertTrue(dow.getNumericDayOfWeek() == 1);
dow = new DayOfWeek(3, 1, 1904);
assertTrue(dow.getDayOfWeek().compareTo("Tuesday") == 0);
assertTrue(dow.getNumericDayOfWeek() == 3);
}
#Test
public void secondValidLeapYearBoundaries() {
DayOfWeek dow = new DayOfWeek(2, 28, 1908);
assertTrue(dow.getDayOfWeek().compareTo("Friday") == 0);
assertTrue(dow.getNumericDayOfWeek() == 6);
dow = new DayOfWeek(3, 1, 1908);
assertTrue(dow.getDayOfWeek().compareTo("Sunday") == 0);
assertTrue(dow.getNumericDayOfWeek() == 1);
}
}
Here is the line the error is pointing to, in the secondValidLeapYearBoundaries()
assertTrue(dow.getDayOfWeek().compareTo("Friday") == 0);
does anyone know how to fix all these problems?
How to fix it? Print out the return value of dow.getDayOfWeek() for your failing case (or examine it in a debugger) to see what it is giving you, then single-stepping through the function to find out why. In this particular case, it's probably the constructor rather than getDayOfWeek since the latter is simply giving you information calculated by the former.
That's how you solve almost any problem, in coding and most other fields that are deterministic. Confirm that there's a problem then reexamine the steps to see where the problem was introduced.
I've got a String like this: 2013-04-19, and I want to change it into : April 19th 2013. I know there is some classes in Java like SimpleDateFormat, but I don't know what kind of function I should use. Maybe I need to choose the class Pattern? I need some help.
Try the following, which should give you correct "th", "st", "rd" and "nd" for days.
public static String getDayOfMonthSuffix(final int n) {
if (n >= 11 && n <= 13) {
return "th";
}
switch (n % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
public static void main(String[] args) throws ParseException {
Date d = new SimpleDateFormat("yyyy-MM-dd").parse("2013-04-19");
int day = Integer.parseInt(new java.text.SimpleDateFormat("dd").format(d));
SimpleDateFormat sdf = new SimpleDateFormat("MMMMM dd'" + getDayOfMonthSuffix(day) + "' yyyy");
String s = sdf.format(d);
System.out.println(s);
}
Which will print April 19th 2013
(Day termination adapted from this post)
Try this:
String originalDate = "2013-04-19";
Date date = null;
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(originalDate);
} catch (Exception e) {
}
String formattedDate = new SimpleDateFormat("MMMM dd yyyy").format(date);
Will not print the st, nd, rd, etc.
Just using parse method from SimpleDateFormat class
try this:
new SimpleDateFormat("MMM dd YYYY").parse("2013-04-19");
I have a method that gets a string and change that to a particular date format but the thing is the date will be any format
For Example
16 July 2012
March 20 2012
2012 March 20
So I need to detect the string is in which file format.
I use the below code to test it but I get exception if the file format changes.
private String getUpdatedDate(String updated) {
Date date;
String formatedDate = null;
try {
date = new SimpleDateFormat("d MMMM yyyy", Locale.ENGLISH)
.parse(updated);
formatedDate = getDateFormat().format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return formatedDate;
}
Perhaps the easiest solution is to build a collection of date formats you can reasonably expect, and then try the input against each one in turn.
You may want to flag ambiguous inputs e.g. is 2012/5/6 the 5th June or 6th May ?
BalusC wrote a simple DateUtil which serves for many cases. You may need to extend this to satisfy your requirements.
Here is the link: https://balusc.omnifaces.org/2007/09/dateutil.html
and the method you need to look for determineDateFormat()
If you're using Joda Time (awesome library btw) you can do this quite easily:
DateTimeParser[] dateParsers = {
DateTimeFormat.forPattern("yyyy-MM-dd HH").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd").getParser() };
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, dateParsers).toFormatter();
DateTime date1 = formatter.parseDateTime("2012-07-03");
DateTime date2 = formatter.parseDateTime("2012-07-03 01");
Apache commons has a utility method to solve this problem . The org.apache.commons.lang.time.DateUtils class has a method parseDateStrictly
public static Date parseDateStrictly(String str,
String[] parsePatterns)
throws ParseException
Parameters:
str - the date to parse, not null
parsePatterns - the date format patterns to use, see SimpleDateFormat, not null
Parses a string representing a date by trying a variety of different parsers.
The parse will try each parse pattern in turn. A parse is only deemed successful if it parses the whole of the input string. If no parse patterns match, a ParseException is thrown.
The parser parses strictly - it does not allow for dates such as "February 942, 1996".
FTA (https://github.com/tsegall/fta) is designed to solve exactly this problem (among others). Here is an example:
import java.util.Locale;
import com.cobber.fta.dates.DateTimeParser;
import com.cobber.fta.dates.DateTimeParser.DateResolutionMode;
public abstract class DetermineDateFormat {
public static void main(final String[] args) {
final DateTimeParser dtp = new DateTimeParser(DateResolutionMode.MonthFirst, Locale.ENGLISH);
System.err.println(dtp.determineFormatString("26 July 2012"));
System.err.println(dtp.determineFormatString("March 9 2012"));
// Note: Detected as MM/dd/yyyy despite being ambiguous as we indicated MonthFirst above when insufficient data
System.err.println(dtp.determineFormatString("07/04/2012"));
System.err.println(dtp.determineFormatString("2012 March 20"));
System.err.println(dtp.determineFormatString("2012/04/09 18:24:12"));
}
Which will give the following output:
MMMM d yyyy
MM/dd/yyyy
yyyy MMMM dd
yyyy/MM/dd HH:mm:ss
Decide which formats are expected, and try to parse the date with each format, one after the other. Stop as soon as one of the formats parses the date without exception.
Click to see the result
Use the regex to parse the string for date. This regex can detect any kind of date format. The sample code here is not including time yet. You can change the code to add more parts of the date like time and time zone...The month name is depending on default language locale of the system.
import java.io.IOException;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DateUtils {
static String MONTH="";
static String dateRegEx="";
static Pattern DatePattern;
static HashMap<String, Integer> monthMap = new HashMap<String, Integer>();
static {
initializeMonthName();
dateRegEx="(?i)(\\d{1,4}|"+MONTH+")[-|/|.|\\s+]?(\\d{1,2}|"+MONTH+")[-|/|.|,]?[\\s+]?(\\d{1,4}|"+MONTH+")[\\s+|\\t|T]?(\\d{0,2}):?(\\d{0,2}):?(\\d{0,2})[.|,]?[\\s]?(\\d{0,3})?([+|-])?(\\d{0,2})[:]?(\\d{0,2})[\\s+]?([A|P]M)?";
DatePattern = Pattern.compile(dateRegEx);
}
private static void initializeMonthName() {
String[] monthName=getMonthString(true);
for(int i=0;i<12;i++){
monthMap.put(monthName[i].toLowerCase(), Integer.valueOf(i+1));
}
monthName=getMonthString(false);
for(int i=0;i<12;i++){
monthMap.put(monthName[i].toLowerCase(), Integer.valueOf(i+1));
}
Iterator<String> it = monthMap.keySet().iterator();
while(it.hasNext()){
String month=it.next();
if(MONTH.isEmpty()){
MONTH=month;
}else{
MONTH=MONTH + "|" + month;
}
}
}
public static boolean isInteger(Object object) {
if(object instanceof Integer) {
return true;
} else {
try{
Integer.parseInt(object.toString());
}catch(Exception e) {
return false;
}
}
return true;
}
public static String[] getMonthString(boolean isShort) {
DateFormatSymbols dfs = new DateFormatSymbols();
if (isShort) {
return dfs.getShortMonths();
} else {
return dfs.getMonths();
}
}
public static int getMonthMap(String value) {
if(monthMap.get(value)==null){
return 0;
}
return monthMap.get(value).intValue();
}
public static long parseDate(String value){
Matcher matcher = DatePattern.matcher(value);
int Year=0, Month=0, Day=0;
boolean isYearFound=false;
boolean isMonthFound=false;
boolean isDayFound=false;
if(matcher.find()) {
for(int i=1;i<matcher.groupCount();i++){
String data=matcher.group(i)==null?"":matcher.group(i);
if(data.equalsIgnoreCase("null")){
data="";
}
//System.out.println(String.valueOf(i) + ": " + data);
switch(i){
case 1:
if(!data.isEmpty()){
if(isInteger(data)){
Integer YMD = Integer.valueOf(data);
if(YMD==0){
return 0;
}
if(YMD>31){
Year = YMD.intValue();
isYearFound = true;
}else if(YMD>12){
Day = YMD.intValue();
isDayFound = true;
}else {
Month=YMD.intValue();
isMonthFound=true;
}
}else {
Month = getMonthMap(data.toLowerCase());
if(Month==0){
return 0;
}
isMonthFound=true;
}
}else {
return 0;
}
break;
case 2:
if(!data.isEmpty()){
if(isInteger(data)){
Integer YMD = Integer.valueOf(data);
if(YMD==0){
return 0;
}
if(YMD>31){
if(isYearFound) {
return 0;
}
Year = YMD.intValue();
isYearFound = true;
}else if(YMD>12){
if(isDayFound) {
return 0;
}
Day = YMD.intValue();
isDayFound = true;
}else {
if(isMonthFound){
Day=YMD.intValue();
isDayFound=true;
}else{
Month=YMD.intValue();
isMonthFound=true;
}
}
}else {
if(isMonthFound){
Day=Month;
isDayFound=true;
}
Month = getMonthMap(data.toLowerCase());
if(Month==0){
return 0;
}
isMonthFound=true;
}
}else {
return 0;
}
break;
case 3:
if(!data.isEmpty()){
if(isInteger(data)){
Integer YMD = Integer.valueOf(data);
if(YMD==0){
return 0;
}
if(YMD>31){
if(isYearFound) {
return 0;
}
Year = YMD.intValue();
isYearFound = true;
}else if(YMD>12){
if(isDayFound) {
return 0;
}
Day = YMD.intValue();
isDayFound = true;
}else {
if(isMonthFound){
Day=YMD.intValue();
isDayFound=true;
}else {
Month = YMD.intValue();
isMonthFound=true;
}
}
}else {
if(isMonthFound){
Day=Month;
isDayFound=true;
}
Month = getMonthMap(data.toLowerCase());
if(Month==0){
return 0;
}
isMonthFound=true;
}
}else {
return 0;
}
break;
case 4:
//hour
break;
case 5:
//minutes
break;
case 6:
//second
break;
case 7:
//millisecond
break;
case 8:
//time zone +/-
break;
case 9:
//time zone hour
break;
case 10:
// time zone minute
break;
case 11:
//AM/PM
break;
}
}
}
Calendar c = Calendar.getInstance();
c.set(Year, Month-1, Day, 0, 0);
return c.getTime().getTime();
}
public static void main(String[] argv) throws IOException {
long d= DateUtils.parseDate("16 July 2012");
Date dt = new Date(d);
SimpleDateFormat df2 = new SimpleDateFormat("d MMMM yyyy");
String dateText = df2.format(dt);
System.out.println(dateText);
d= DateUtils.parseDate("March 20 2012");
dt = new Date(d);
dateText = df2.format(dt);
System.out.println(dateText);
d= DateUtils.parseDate("2012 March 20");
dt = new Date(d);
dateText = df2.format(dt);
System.out.println(dateText);
}
}
public static String detectDateFormat(Context context, String inputDate, String requiredFormat) {
String tempDate = inputDate.replace("/", "").replace("-", "").replace(" ", "");
String dateFormat = "";
if (tempDate.matches("([0-12]{2})([0-31]{2})([0-9]{4})")) {
dateFormat = "MMddyyyy";
} else if (tempDate.matches("([0-31]{2})([0-12]{2})([0-9]{4})")) {
dateFormat = "ddMMyyyy";
} else if (tempDate.matches("([0-9]{4})([0-12]{2})([0-31]{2})")) {
dateFormat = "yyyyMMdd";
} else if (tempDate.matches("([0-9]{4})([0-31]{2})([0-12]{2})")) {
dateFormat = "yyyyddMM";
} else if (tempDate.matches("([0-31]{2})([a-z]{3})([0-9]{4})")) {
dateFormat = "ddMMMyyyy";
} else if (tempDate.matches("([a-z]{3})([0-31]{2})([0-9]{4})")) {
dateFormat = "MMMddyyyy";
} else if (tempDate.matches("([0-9]{4})([a-z]{3})([0-31]{2})")) {
dateFormat = "yyyyMMMdd";
} else if (tempDate.matches("([0-9]{4})([0-31]{2})([a-z]{3})")) {
dateFormat = "yyyyddMMM";
} else {
}
try {
String formattedDate = new SimpleDateFormat(requiredFormat, Locale.ENGLISH).format(new SimpleDateFormat(dateFormat).parse(tempDate));
Toast.makeText(context, formattedDate, Toast.LENGTH_SHORT).show();
return formattedDate;
} catch (Exception e) {
Toast.makeText(context, "Please check the date format", Toast.LENGTH_SHORT).show();
return "";
}
}
I encountered this issue as well, where at some places:
I did the same thing having a collection of format which matches my need.
Updated my sql query in a way that it returns the date in a format which I can easily parse for e.g. used this in my query TO_CHAR (o.CREATE_TS, 'MM-DD-YYYY')
& while converting in my other desired format used "MM-dd-yyyy" in java to parse and change to desired format.
Hopefully, #2 will help you in atleast few cases.
I'm just wondering if there is a way (maybe with regex) to validate that an input on a Java desktop app is exactly a string formatted as: "YYYY-MM-DD".
Use the following regular expression:
^\d{4}-\d{2}-\d{2}$
as in
if (str.matches("\\d{4}-\\d{2}-\\d{2}")) {
...
}
With the matches method, the anchors ^ and $ (beginning and end of string, respectively) are present implicitly.
The pattern above checks conformance with the general “shape” of a date, but it will accept more invalid than valid dates. You may be surprised to learn that checking for valid dates — including leap years! — is possible using a regular expression, but not advisable. Borrowing from an answer elsewhere by Kuldeep, we can all find amusement and admiration for persistence in
((18|19|20)[0-9]{2}[\-.](0[13578]|1[02])[\-.](0[1-9]|[12][0-9]|3[01]))|(18|19|20)[0-9]{2}[\-.](0[469]|11)[\-.](0[1-9]|[12][0-9]|30)|(18|19|20)[0-9]{2}[\-.](02)[\-.](0[1-9]|1[0-9]|2[0-8])|(((18|19|20)(04|08|[2468][048]|[13579][26]))|2000)[\-.](02)[\-.]29
In a production context, your colleagues will appreciate a more straightforward implementation. Remember, the first rule of optimization is Don’t!
You need more than a regex, for example "9999-99-00" isn't a valid date. There's a SimpleDateFormat class that's built to do this. More heavyweight, but more comprehensive.
e.g.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
boolean isValidDate(string input) {
try {
format.parse(input);
return true;
}
catch(ParseException e){
return false;
}
}
Unfortunately, SimpleDateFormat is both heavyweight and not thread-safe.
Putting it all together:
REGEX doesn't validate values (like "2010-19-19")
SimpleDateFormat does not check format ("2010-1-2", "1-0002-003" are accepted)
it's necessary to use both to validate format and value:
public static boolean isValid(String text) {
if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d"))
return false;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setLenient(false);
try {
df.parse(text);
return true;
} catch (ParseException ex) {
return false;
}
}
A ThreadLocal can be used to avoid the creation of a new SimpleDateFormat for each call.
It is needed in a multithread context since the SimpleDateFormat is not thread safe:
private static final ThreadLocal<SimpleDateFormat> format = new ThreadLocal<SimpleDateFormat>() {
#Override
protected SimpleDateFormat initialValue() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setLenient(false);
System.out.println("created");
return df;
}
};
public static boolean isValid(String text) {
if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d"))
return false;
try {
format.get().parse(text);
return true;
} catch (ParseException ex) {
return false;
}
}
(same can be done for a Matcher, that also is not thread safe)
This will do it regex: "^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$"
This will take care of valid formats and valid dates. It will not validate the correct days of the month i.e. leap year.
String regex = "^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$";
Assert.assertTrue("Date: matched.", Pattern.matches(regex, "2011-1-1"));
Assert.assertFalse("Date (month): not matched.", Pattern.matches(regex, "2011-13-1"));
Good luck!
I would go with a simple regex which will check that days doesn't have more than 31 days and months no more than 12. Something like:
(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-((18|19|20|21)\\d\\d)
This is the format "dd-MM-yyyy". You can tweak it to your needs (for example take off the ? to make the leading 0 required - now its optional), and then use a custom logic to cut down to the specific rules like leap years February number of days case, and other months number of days cases. See the DateChecker code below.
I am choosing this approach since I tested that this is the best one when performance is taken into account. I checked this (1st) approach versus 2nd approach of validating a date against a regex that takes care of the other use cases, and 3rd approach of using the same simple regex above in combination with SimpleDateFormat.parse(date).
The 1st approach was 4 times faster than the 2nd approach, and 8 times faster than the 3rd approach. See the self contained date checker and performance tester main class at the bottom.
One thing that I left unchecked is the joda time approach(s). (The more efficient date/time library).
Date checker code:
class DateChecker {
private Matcher matcher;
private Pattern pattern;
public DateChecker(String regex) {
pattern = Pattern.compile(regex);
}
/**
* Checks if the date format is a valid.
* Uses the regex pattern to match the date first.
* Than additionally checks are performed on the boundaries of the days taken the month into account (leap years are covered).
*
* #param date the date that needs to be checked.
* #return if the date is of an valid format or not.
*/
public boolean check(final String date) {
matcher = pattern.matcher(date);
if (matcher.matches()) {
matcher.reset();
if (matcher.find()) {
int day = Integer.parseInt(matcher.group(1));
int month = Integer.parseInt(matcher.group(2));
int year = Integer.parseInt(matcher.group(3));
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: return day < 32;
case 4:
case 6:
case 9:
case 11: return day < 31;
case 2:
int modulo100 = year % 100;
//http://science.howstuffworks.com/science-vs-myth/everyday-myths/question50.htm
if ((modulo100 == 0 && year % 400 == 0) || (modulo100 != 0 && year % LEAP_STEP == 0)) {
//its a leap year
return day < 30;
} else {
return day < 29;
}
default:
break;
}
}
}
return false;
}
public String getRegex() {
return pattern.pattern();
}
}
Date checking/testing and performance testing:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Tester {
private static final String[] validDateStrings = new String[]{
"1-1-2000", //leading 0s for day and month optional
"01-1-2000", //leading 0 for month only optional
"1-01-2000", //leading 0 for day only optional
"01-01-1800", //first accepted date
"31-12-2199", //last accepted date
"31-01-2000", //January has 31 days
"31-03-2000", //March has 31 days
"31-05-2000", //May has 31 days
"31-07-2000", //July has 31 days
"31-08-2000", //August has 31 days
"31-10-2000", //October has 31 days
"31-12-2000", //December has 31 days
"30-04-2000", //April has 30 days
"30-06-2000", //June has 30 days
"30-09-2000", //September has 30 days
"30-11-2000", //November has 30 days
};
private static final String[] invalidDateStrings = new String[]{
"00-01-2000", //there is no 0-th day
"01-00-2000", //there is no 0-th month
"31-12-1799", //out of lower boundary date
"01-01-2200", //out of high boundary date
"32-01-2000", //January doesn't have 32 days
"32-03-2000", //March doesn't have 32 days
"32-05-2000", //May doesn't have 32 days
"32-07-2000", //July doesn't have 32 days
"32-08-2000", //August doesn't have 32 days
"32-10-2000", //October doesn't have 32 days
"32-12-2000", //December doesn't have 32 days
"31-04-2000", //April doesn't have 31 days
"31-06-2000", //June doesn't have 31 days
"31-09-2000", //September doesn't have 31 days
"31-11-2000", //November doesn't have 31 days
"001-02-2000", //SimpleDateFormat valid date (day with leading 0s) even with lenient set to false
"1-0002-2000", //SimpleDateFormat valid date (month with leading 0s) even with lenient set to false
"01-02-0003", //SimpleDateFormat valid date (year with leading 0s) even with lenient set to false
"01.01-2000", //. invalid separator between day and month
"01-01.2000", //. invalid separator between month and year
"01/01-2000", /// invalid separator between day and month
"01-01/2000", /// invalid separator between month and year
"01_01-2000", //_ invalid separator between day and month
"01-01_2000", //_ invalid separator between month and year
"01-01-2000-12345", //only whole string should be matched
"01-13-2000", //month bigger than 13
};
/**
* These constants will be used to generate the valid and invalid boundary dates for the leap years. (For no leap year, Feb. 28 valid and Feb. 29 invalid; for a leap year Feb. 29 valid and Feb. 30 invalid)
*/
private static final int LEAP_STEP = 4;
private static final int YEAR_START = 1800;
private static final int YEAR_END = 2199;
/**
* This date regex will find matches for valid dates between 1800 and 2199 in the format of "dd-MM-yyyy".
* The leading 0 is optional.
*/
private static final String DATE_REGEX = "((0?[1-9]|[12][0-9]|3[01])-(0?[13578]|1[02])-(18|19|20|21)[0-9]{2})|((0?[1-9]|[12][0-9]|30)-(0?[469]|11)-(18|19|20|21)[0-9]{2})|((0?[1-9]|1[0-9]|2[0-8])-(0?2)-(18|19|20|21)[0-9]{2})|(29-(0?2)-(((18|19|20|21)(04|08|[2468][048]|[13579][26]))|2000))";
/**
* This date regex is similar to the first one, but with the difference of matching only the whole string. So "01-01-2000-12345" won't pass with a match.
* Keep in mind that String.matches tries to match only the whole string.
*/
private static final String DATE_REGEX_ONLY_WHOLE_STRING = "^" + DATE_REGEX + "$";
/**
* The simple regex (without checking for 31 day months and leap years):
*/
private static final String DATE_REGEX_SIMPLE = "(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-((18|19|20|21)\\d\\d)";
/**
* This date regex is similar to the first one, but with the difference of matching only the whole string. So "01-01-2000-12345" won't pass with a match.
*/
private static final String DATE_REGEX_SIMPLE_ONLY_WHOLE_STRING = "^" + DATE_REGEX_SIMPLE + "$";
private static final SimpleDateFormat SDF = new SimpleDateFormat("dd-MM-yyyy");
static {
SDF.setLenient(false);
}
private static final DateChecker dateValidatorSimple = new DateChecker(DATE_REGEX_SIMPLE);
private static final DateChecker dateValidatorSimpleOnlyWholeString = new DateChecker(DATE_REGEX_SIMPLE_ONLY_WHOLE_STRING);
/**
* #param args
*/
public static void main(String[] args) {
DateTimeStatistics dateTimeStatistics = new DateTimeStatistics();
boolean shouldMatch = true;
for (int i = 0; i < validDateStrings.length; i++) {
String validDate = validDateStrings[i];
matchAssertAndPopulateTimes(
dateTimeStatistics,
shouldMatch, validDate);
}
shouldMatch = false;
for (int i = 0; i < invalidDateStrings.length; i++) {
String invalidDate = invalidDateStrings[i];
matchAssertAndPopulateTimes(dateTimeStatistics,
shouldMatch, invalidDate);
}
for (int year = YEAR_START; year < (YEAR_END + 1); year++) {
FebruaryBoundaryDates februaryBoundaryDates = createValidAndInvalidFebruaryBoundaryDateStringsFromYear(year);
shouldMatch = true;
matchAssertAndPopulateTimes(dateTimeStatistics,
shouldMatch, februaryBoundaryDates.getValidFebruaryBoundaryDateString());
shouldMatch = false;
matchAssertAndPopulateTimes(dateTimeStatistics,
shouldMatch, februaryBoundaryDates.getInvalidFebruaryBoundaryDateString());
}
dateTimeStatistics.calculateAvarageTimesAndPrint();
}
private static void matchAssertAndPopulateTimes(
DateTimeStatistics dateTimeStatistics,
boolean shouldMatch, String date) {
dateTimeStatistics.addDate(date);
matchAndPopulateTimeToMatch(date, DATE_REGEX, shouldMatch, dateTimeStatistics.getTimesTakenWithDateRegex());
matchAndPopulateTimeToMatch(date, DATE_REGEX_ONLY_WHOLE_STRING, shouldMatch, dateTimeStatistics.getTimesTakenWithDateRegexOnlyWholeString());
boolean matchesSimpleDateFormat = matchWithSimpleDateFormatAndPopulateTimeToMatchAndReturnMatches(date, dateTimeStatistics.getTimesTakenWithSimpleDateFormatParse());
matchAndPopulateTimeToMatchAndReturnMatchesAndCheck(
dateTimeStatistics.getTimesTakenWithDateRegexSimple(), shouldMatch,
date, matchesSimpleDateFormat, DATE_REGEX_SIMPLE);
matchAndPopulateTimeToMatchAndReturnMatchesAndCheck(
dateTimeStatistics.getTimesTakenWithDateRegexSimpleOnlyWholeString(), shouldMatch,
date, matchesSimpleDateFormat, DATE_REGEX_SIMPLE_ONLY_WHOLE_STRING);
matchAndPopulateTimeToMatch(date, dateValidatorSimple, shouldMatch, dateTimeStatistics.getTimesTakenWithdateValidatorSimple());
matchAndPopulateTimeToMatch(date, dateValidatorSimpleOnlyWholeString, shouldMatch, dateTimeStatistics.getTimesTakenWithdateValidatorSimpleOnlyWholeString());
}
private static void matchAndPopulateTimeToMatchAndReturnMatchesAndCheck(
List<Long> times,
boolean shouldMatch, String date, boolean matchesSimpleDateFormat, String regex) {
boolean matchesFromRegex = matchAndPopulateTimeToMatchAndReturnMatches(date, regex, times);
assert !((matchesSimpleDateFormat && matchesFromRegex) ^ shouldMatch) : "Parsing with SimpleDateFormat and date:" + date + "\nregex:" + regex + "\nshouldMatch:" + shouldMatch;
}
private static void matchAndPopulateTimeToMatch(String date, String regex, boolean shouldMatch, List<Long> times) {
boolean matches = matchAndPopulateTimeToMatchAndReturnMatches(date, regex, times);
assert !(matches ^ shouldMatch) : "date:" + date + "\nregex:" + regex + "\nshouldMatch:" + shouldMatch;
}
private static void matchAndPopulateTimeToMatch(String date, DateChecker dateValidator, boolean shouldMatch, List<Long> times) {
long timestampStart;
long timestampEnd;
boolean matches;
timestampStart = System.nanoTime();
matches = dateValidator.check(date);
timestampEnd = System.nanoTime();
times.add(timestampEnd - timestampStart);
assert !(matches ^ shouldMatch) : "date:" + date + "\ndateValidator with regex:" + dateValidator.getRegex() + "\nshouldMatch:" + shouldMatch;
}
private static boolean matchAndPopulateTimeToMatchAndReturnMatches(String date, String regex, List<Long> times) {
long timestampStart;
long timestampEnd;
boolean matches;
timestampStart = System.nanoTime();
matches = date.matches(regex);
timestampEnd = System.nanoTime();
times.add(timestampEnd - timestampStart);
return matches;
}
private static boolean matchWithSimpleDateFormatAndPopulateTimeToMatchAndReturnMatches(String date, List<Long> times) {
long timestampStart;
long timestampEnd;
boolean matches = true;
timestampStart = System.nanoTime();
try {
SDF.parse(date);
} catch (ParseException e) {
matches = false;
} finally {
timestampEnd = System.nanoTime();
times.add(timestampEnd - timestampStart);
}
return matches;
}
private static FebruaryBoundaryDates createValidAndInvalidFebruaryBoundaryDateStringsFromYear(int year) {
FebruaryBoundaryDates februaryBoundaryDates;
int modulo100 = year % 100;
//http://science.howstuffworks.com/science-vs-myth/everyday-myths/question50.htm
if ((modulo100 == 0 && year % 400 == 0) || (modulo100 != 0 && year % LEAP_STEP == 0)) {
februaryBoundaryDates = new FebruaryBoundaryDates(
createFebruaryDateFromDayAndYear(29, year),
createFebruaryDateFromDayAndYear(30, year)
);
} else {
februaryBoundaryDates = new FebruaryBoundaryDates(
createFebruaryDateFromDayAndYear(28, year),
createFebruaryDateFromDayAndYear(29, year)
);
}
return februaryBoundaryDates;
}
private static String createFebruaryDateFromDayAndYear(int day, int year) {
return String.format("%d-02-%d", day, year);
}
static class FebruaryBoundaryDates {
private String validFebruaryBoundaryDateString;
String invalidFebruaryBoundaryDateString;
public FebruaryBoundaryDates(String validFebruaryBoundaryDateString,
String invalidFebruaryBoundaryDateString) {
super();
this.validFebruaryBoundaryDateString = validFebruaryBoundaryDateString;
this.invalidFebruaryBoundaryDateString = invalidFebruaryBoundaryDateString;
}
public String getValidFebruaryBoundaryDateString() {
return validFebruaryBoundaryDateString;
}
public void setValidFebruaryBoundaryDateString(
String validFebruaryBoundaryDateString) {
this.validFebruaryBoundaryDateString = validFebruaryBoundaryDateString;
}
public String getInvalidFebruaryBoundaryDateString() {
return invalidFebruaryBoundaryDateString;
}
public void setInvalidFebruaryBoundaryDateString(
String invalidFebruaryBoundaryDateString) {
this.invalidFebruaryBoundaryDateString = invalidFebruaryBoundaryDateString;
}
}
static class DateTimeStatistics {
private List<String> dates = new ArrayList<String>();
private List<Long> timesTakenWithDateRegex = new ArrayList<Long>();
private List<Long> timesTakenWithDateRegexOnlyWholeString = new ArrayList<Long>();
private List<Long> timesTakenWithDateRegexSimple = new ArrayList<Long>();
private List<Long> timesTakenWithDateRegexSimpleOnlyWholeString = new ArrayList<Long>();
private List<Long> timesTakenWithSimpleDateFormatParse = new ArrayList<Long>();
private List<Long> timesTakenWithdateValidatorSimple = new ArrayList<Long>();
private List<Long> timesTakenWithdateValidatorSimpleOnlyWholeString = new ArrayList<Long>();
public List<String> getDates() {
return dates;
}
public List<Long> getTimesTakenWithDateRegex() {
return timesTakenWithDateRegex;
}
public List<Long> getTimesTakenWithDateRegexOnlyWholeString() {
return timesTakenWithDateRegexOnlyWholeString;
}
public List<Long> getTimesTakenWithDateRegexSimple() {
return timesTakenWithDateRegexSimple;
}
public List<Long> getTimesTakenWithDateRegexSimpleOnlyWholeString() {
return timesTakenWithDateRegexSimpleOnlyWholeString;
}
public List<Long> getTimesTakenWithSimpleDateFormatParse() {
return timesTakenWithSimpleDateFormatParse;
}
public List<Long> getTimesTakenWithdateValidatorSimple() {
return timesTakenWithdateValidatorSimple;
}
public List<Long> getTimesTakenWithdateValidatorSimpleOnlyWholeString() {
return timesTakenWithdateValidatorSimpleOnlyWholeString;
}
public void addDate(String date) {
dates.add(date);
}
public void addTimesTakenWithDateRegex(long time) {
timesTakenWithDateRegex.add(time);
}
public void addTimesTakenWithDateRegexOnlyWholeString(long time) {
timesTakenWithDateRegexOnlyWholeString.add(time);
}
public void addTimesTakenWithDateRegexSimple(long time) {
timesTakenWithDateRegexSimple.add(time);
}
public void addTimesTakenWithDateRegexSimpleOnlyWholeString(long time) {
timesTakenWithDateRegexSimpleOnlyWholeString.add(time);
}
public void addTimesTakenWithSimpleDateFormatParse(long time) {
timesTakenWithSimpleDateFormatParse.add(time);
}
public void addTimesTakenWithdateValidatorSimple(long time) {
timesTakenWithdateValidatorSimple.add(time);
}
public void addTimesTakenWithdateValidatorSimpleOnlyWholeString(long time) {
timesTakenWithdateValidatorSimpleOnlyWholeString.add(time);
}
private void calculateAvarageTimesAndPrint() {
long[] sumOfTimes = new long[7];
int timesSize = timesTakenWithDateRegex.size();
for (int i = 0; i < timesSize; i++) {
sumOfTimes[0] += timesTakenWithDateRegex.get(i);
sumOfTimes[1] += timesTakenWithDateRegexOnlyWholeString.get(i);
sumOfTimes[2] += timesTakenWithDateRegexSimple.get(i);
sumOfTimes[3] += timesTakenWithDateRegexSimpleOnlyWholeString.get(i);
sumOfTimes[4] += timesTakenWithSimpleDateFormatParse.get(i);
sumOfTimes[5] += timesTakenWithdateValidatorSimple.get(i);
sumOfTimes[6] += timesTakenWithdateValidatorSimpleOnlyWholeString.get(i);
}
System.out.println("AVG from timesTakenWithDateRegex (in nanoseconds):" + (double) sumOfTimes[0] / timesSize);
System.out.println("AVG from timesTakenWithDateRegexOnlyWholeString (in nanoseconds):" + (double) sumOfTimes[1] / timesSize);
System.out.println("AVG from timesTakenWithDateRegexSimple (in nanoseconds):" + (double) sumOfTimes[2] / timesSize);
System.out.println("AVG from timesTakenWithDateRegexSimpleOnlyWholeString (in nanoseconds):" + (double) sumOfTimes[3] / timesSize);
System.out.println("AVG from timesTakenWithSimpleDateFormatParse (in nanoseconds):" + (double) sumOfTimes[4] / timesSize);
System.out.println("AVG from timesTakenWithDateRegexSimple + timesTakenWithSimpleDateFormatParse (in nanoseconds):" + (double) (sumOfTimes[2] + sumOfTimes[4]) / timesSize);
System.out.println("AVG from timesTakenWithDateRegexSimpleOnlyWholeString + timesTakenWithSimpleDateFormatParse (in nanoseconds):" + (double) (sumOfTimes[3] + sumOfTimes[4]) / timesSize);
System.out.println("AVG from timesTakenWithdateValidatorSimple (in nanoseconds):" + (double) sumOfTimes[5] / timesSize);
System.out.println("AVG from timesTakenWithdateValidatorSimpleOnlyWholeString (in nanoseconds):" + (double) sumOfTimes[6] / timesSize);
}
}
static class DateChecker {
private Matcher matcher;
private Pattern pattern;
public DateChecker(String regex) {
pattern = Pattern.compile(regex);
}
/**
* Checks if the date format is a valid.
* Uses the regex pattern to match the date first.
* Than additionally checks are performed on the boundaries of the days taken the month into account (leap years are covered).
*
* #param date the date that needs to be checked.
* #return if the date is of an valid format or not.
*/
public boolean check(final String date) {
matcher = pattern.matcher(date);
if (matcher.matches()) {
matcher.reset();
if (matcher.find()) {
int day = Integer.parseInt(matcher.group(1));
int month = Integer.parseInt(matcher.group(2));
int year = Integer.parseInt(matcher.group(3));
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: return day < 32;
case 4:
case 6:
case 9:
case 11: return day < 31;
case 2:
int modulo100 = year % 100;
//http://science.howstuffworks.com/science-vs-myth/everyday-myths/question50.htm
if ((modulo100 == 0 && year % 400 == 0) || (modulo100 != 0 && year % LEAP_STEP == 0)) {
//its a leap year
return day < 30;
} else {
return day < 29;
}
default:
break;
}
}
}
return false;
}
public String getRegex() {
return pattern.pattern();
}
}
}
Some useful notes:
- to enable the assertions (assert checks) you need to use -ea argument when running the tester. (In eclipse this is done by editing the Run/Debug configuration -> Arguments tab -> VM Arguments -> insert "-ea"
- the regex above is bounded to years 1800 to 2199
- you don't need to use ^ at the beginning and $ at the end to match only the whole date string. The String.matches takes care of that.
- make sure u check the valid and invalid cases and change them according the rules that you have.
- the "only whole string" version of each regex gives the same speed as the "normal" version (the one without ^ and $). If you see performance differences this is because java "gets used" to processing the same instructions so the time lowers. If you switch the lines where the "normal" and the "only whole string" version execute, you will see this proven.
Hope this helps someone!
Cheers,
Despot
java.time
The proper (and easy) way to do date/time validation using Java 8+ is to use the java.time.format.DateTimeFormatter class. Using a regex for validation isn't really ideal for dates. For the example case in this question:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
try {
LocalDate date = formatter.parse(text, LocalDate::from);
} catch (DateTimeParseException e) {
// Thrown if text could not be parsed in the specified format
}
This code will parse the text, validate that it is a valid date, and also return the date as a LocalDate object. Note that the DateTimeFormatter class has a number of static predefined date formats matching ISO standards if your use case matches any of them.
The following regex will accept YYYY-MM-DD (within the range 1600-2999 year) formatted dates taking into consideration leap years:
^((?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:(?:0[13578]|1[02])(-)31)|((0[1,3-9]|1[0-2])(-)(29|30))))$|^(?:(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(-)02(-)29)$|^(?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:0[1-9])|(?:1[0-2]))(-)(?:0[1-9]|1\d|2[0-8])$
Examples:
You can test it here.
Note: if you want to accept one digit as month or day you can use:
^((?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:(?:0?[13578]|1[02])(-)31)|((0?[1,3-9]|1[0-2])(-)(29|30))))$|^(?:(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(-)0?2(-)29)$|^(?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:0?[1-9])|(?:1[0-2]))(-)(?:0?[1-9]|1\d|2[0-8])$
I have created the above regex starting from this solution
The pattern yyyy-MM-dd is the default pattern used by LocalDate#parse. Therefore, all you need to do is to pass your date string to this method and check if it is successfully parsed or some exception has occurred.
Demo:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
String[] arr = { "2022-11-29", "0000-00-00", "2022-1-2", "2022-02-29" };
for (String s : arr) {
try {
System.out.println("================================");
System.out.println(LocalDate.parse(s) + " is a valid date ");
} catch (DateTimeParseException e) {
System.out.println(e.getMessage());
// Recommended; so that the caller can handle it appropriately
// throw new IllegalArgumentException("Invalid date");
}
}
}
}
Output:
================================
2022-11-29 is a valid date
================================
Text '0000-00-00' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 0
================================
Text '2022-1-2' could not be parsed at index 5
================================
Text '2022-02-29' could not be parsed: Invalid date 'February 29' as '2022' is not a leap year
Some important notes:
java.time types follow ISO 8601 standards and therefore you do need to specify a DateTimeFormatter to parse a date-time string which is in ISO 8601 format.
The java.time API, released with Java-8 in March 2014, supplanted the error-prone legacy date-time API. Since then, it has been strongly recommended to use this modern date-time API. Learn more about the modern Date-Time API from Trail: Date Time.
Construct a SimpleDateFormat with the mask, and then call:
SimpleDateFormat.parse(String s, ParsePosition p)
For fine control, consider an InputVerifier using the SimpleDateFormat("YYYY-MM-dd") suggested by Steve B.
Below added code is working for me if you are using pattern
dd-MM-yyyy.
public boolean isValidDate(String date) {
boolean check;
String date1 = "^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-([12][0-9]{3})$";
check = date.matches(date1);
return check;
}
If you want a simple regex then it won't be accurate.
https://www.freeformatter.com/java-regex-tester.html#ad-output offers a tool to test your Java regex. Also, at the bottom you can find some suggested regexes for validating a date.
ISO date format (yyyy-mm-dd):
^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$
ISO date format (yyyy-mm-dd) with separators '-' or '/' or '.' or ' '. Forces usage of same separator accross date.
^[0-9]{4}([- /.])(((0[13578]|(10|12))\1(0[1-9]|[1-2][0-9]|3[0-1]))|(02\1(0[1-9]|[1-2][0-9]))|((0[469]|11)\1(0[1-9]|[1-2][0-9]|30)))$
United States date format (mm/dd/yyyy)
^(((0[13578]|(10|12))/(0[1-9]|[1-2][0-9]|3[0-1]))|(02/(0[1-9]|[1-2][0-9]))|((0[469]|11)/(0[1-9]|[1-2][0-9]|30)))/[0-9]{4}$
Hours and minutes, 24 hours format (HH:MM):
^(20|21|22|23|[01]\d|\d)((:[0-5]\d){1,2})$
Good luck