I was trying to block incompatible date in input. So I intentionally gave wrong date as string. I set calendar.setLenient to false hoping that it would not allow date to parse. But It pass through it. Below is my code:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Test {
public static void main(String[] args) throws Exception{
try {
String from ="2018-15-18";
String to = "2018-15-18";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calender1 = Calendar.getInstance();
Calendar calender2 = Calendar.getInstance();
calender1.setLenient(false);
calender2.setLenient(false);
calender1.setTime(sdf.parse(from));
calender2.setTime(sdf.parse(to));
Date dtFrom = calender1.getTime();
Date dtTo = calender2.getTime();
System.out.println(sdf.format(dtFrom));
if((from!=null && !from.isEmpty())&&(to!=null && !to.isEmpty())&&(dtFrom!=null && dtTo!=null))
System.out.println("ok");
else
System.out.println("not ok");
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
As I have given wrong date i.e. month 15 does not exist. So I was expecting exception on line calender1.setTime(sdf.parse(from)); but it pass through and printing date value as : 2019-03-18. I did not wanted that. Why is it so? How can I make sure wrong date input should not be entertained further in my code once it is not able to parse.
Related
I am trying to convert date into user required format. I want date in all format.
But formatted date is wrong please help.
package DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormat
{
DateFormat() throws ParseException
{
String dateFormats[] =
{
"YYYY/MM/DD",
"DD/MM/YYYY",
"DD-MM-YYYY",
};
for (int i = 0; i < dateFormats.length; i++)
{
String newDate = new SimpleDateFormat(dateFormats[i]).format(new Date());
System.out.println(newDate);
}
}
public static void main(String[] args) throws ParseException
{
new DateFormat();
}
}
output is
2016/04/98
98/04/2016
98-04-2016
Thank you.
It's going wrong because of java code syntax case sensitive.
Pls check the right date and time pattern at https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Your String array of patterns should be transformed to:
String dateFormats[] =
{
"yyyy/MM/dd",
"dd/MM/yyyy",
"dd-MM-yyyy",
};
D Day in year Number 189
d Day in month Number 10
from https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
So, formats should look like:
String dateFormats[] =
{
"yyyy/MM/dd",
"dd/MM/yyyy",
"dd-MM-yyyy",
};
I'm trying to make it so the user cannot type an invalid date. For example, if the user typed in 2017/03/15 it would throw an error and alert the user that this is invalid (keeping the user bound to current and past dates), or would throw an error for any of the following examples Mar 15 2016 (<-although if anyone had advice to get that to work that would be great), 2016/03/151, 2016/15/03, etc. Then I want to able to parse this into an integer without the time (Hours, Minutes, Seconds). Below is my attempt at making this happen...
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
private void addDVD() {
ConsoleIO con = new ConsoleIO();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date testDate = null;
boolean alive = true;
while (alive) {
String date = con.readString("Please enter Release Date. (yyyy/MM/dd)");
try {
testDate = sdf.parse(date);
alive = false;
} catch (ParseException e) {
con.print("Incorrectly typed date. Try again please. (yyyy/MM/dd)");
}
if (!sdf.format(testDate).equals(date)){
con.print("The date you provided is invalid.");
}
}
DVD dvd = new DVD();
dvd.setReleaseDate(Integer.parseInt(testDate.toString()));
}
You should create a new long for the current time.
long today = System.currentTimeMillis();
Then use that to flag if the date is older than the current date.
if(testDate.getTime() > today) {
System.out.println("bad input");
}
I have to convert string to date such that it should throw error when string is having seconds. For example if I am giving input string as "2015-08-12 12:24:08" I should get an error because I am giving seconds in the string(i.e., 08 here), whereas if I give input as "2015-08-12 12:24" I shouldn't get any error. How can I achieve that?
I have tried below code
String oldstring2 = "2015-08-12 12:24:08";
Date date2 = null;
try {
date2 = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(oldstring2);
System.out.println(date2);
System.out.println("success");
} catch (ParseException e) {
e.printStackTrace();
System.out.println("error");
}
With Java 8 you can use the DateTimeFormatter class. Because this performs strict parsing instead of trying to match from the beginning like SimpleDateFormat does:
String string = "2015-08-12 12:24";
TemporalAccessor ta = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").parse(string);
LocalDate date = LocalDate.from(ta);
the parse method will throw an Exception when you change string to include seconds:
java.time.format.DateTimeParseException: Text '2015-08-12 12:24:12' could not be parsed, unparsed text found at index 16
String oldstring2 = "2015-08-12 12:24";
String[] str = oldstring2.split(" ");
if(str[1]!=null){
String[] str2 = str[1].split(":");
if(str2.length == 2)
System.out.println("success");
else
System.out.println("error");
}
If your input date is exactly like you specified every time, the above code would work.
Please try this:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConversion {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");
Date d = sdf.parse("2015-08-12 12:24:08");
System.out.println(d);
}
}
The Regular expression can achieve the goal:
String oldstring2 = "2015-08-12 12:24";
Pattern p = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?"
+ "((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))"
+ "|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|"
+ "(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|"
+ "([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?"
+ "((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|"
+ "([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))"
+ "(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])()))?$");
if (p.matcher(oldstring2).matches()) {
// do something
} else {
// return the error
}
I want to convert string to date format, but the following way didn't work.
It yields null for birth.
Date birth;
try {
DateFormat formatter ;
formatter = new SimpleDateFormat("dd-MMM-yyyy");
birth = (Date)formatter.parse(birthDate); // birtDate is a string
} catch (ParseException e) {
System.out.println("Exception :"+e);
}
Your answer is right on the money. I put it in a full program and tested it.
It now prints out
Default date format Fri Mar 30 00:00:00 CDT 2012
Our SimpleDateFormat 30-Mar-2012
Our SimpleDateFormat with all uppercase 30-MAR-2012
Here are some tips:
Make sure that you are including the correct imports. Depending on
what is in your classpath, you may have accidentally imported
java.sql.Date or some other rogue import.
Try printing the contents
of birthDate before entering the try block and verify that it really
contains a string of format dd-MMM-yyyy
-
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class BirthDate {
public static void main(String[] args) {
Date birth = null;
String birthDate = "30-MAR-2012";
DateFormat formatter = null;
try {
formatter = new SimpleDateFormat("dd-MMM-yyyy");
birth = (Date) formatter.parse(birthDate); // birtDate is a string
}
catch (ParseException e) {
System.out.println("Exception :" + e);
}
if (birth == null) {
System.out.println("Birth object is still null.");
} else {
System.out.println("Default date format " + birth);
System.out.println("Our SimpleDateFormat " + formatter.format(birth));
System.out.println("Our SimpleDateFormat with all uppercase " + formatter.format(birth).toUpperCase());
}
}
}
Your code works fine. If you care to use Joda Time you can use this. You can go through the documentation to unleash the complete functionality in case you plan to use the time for DB testing and stuff.
import org.joda.time.DateTime;
DateTime dt = new DateTime("YYYY-MM-DD");//new DateTime("2012-03-30")
System.out.println(dt);
All this is my program where i am trying the folowing
Below is my code for Dates functionality...
import java.text.SimpleDateFormat;
import java.util.*;
import java.text.*;
public class DateToCalender {
public static void main(String args[]){
//String strFormat="yyyymmdd";
//DateFormat myDateFormat = new SimpleDateFormat(strFormat);
DateFormat df= new SimpleDateFormat("yyyyMMdd");
df.setLenient(false);
Calendar start=Calendar.getInstance();
try {
Date fromDt =(Date)df.parse("20111207");
//Date myDate = new Date();
//myDate = (Date)myDateFormat.parse("20111207");
//myGDate.setTime(myDate);
start.setTime(fromDt);
start.set(Calendar.MONTH,(start.get(Calendar.MONTH)+1));
System.out.println(start);
System.out.println(start.get(Calendar.YEAR));
System.out.println(start.get(Calendar.MONTH)-1);
System.out.println(start.get(Calendar.DAY_OF_MONTH));
//System.out.println("From My class"+myGDate.get(Calendar.MONTH));
//System.out.println("From My class new month"+(myGDate.get(Calendar.MONTH)+1));
} catch (ParseException e) {
System.out.println("Invalid Date Parser Exception ");
e.printStackTrace();
}
}
}
when iam executing this code iam getting folowwing o/p
java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA
=1,YEAR=2011,MONTH=12,WEEK_OF_YEAR=50,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=341,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=19800000,DST_OFFSET=0]
2011
0
7
**
issue is :
Though iam entering date as 2011/12/07
I am getting year as 2011
month as 0
date as 7
Can some one help in resolving above issue
Could any body please let me know , how this can be resolved .
Don't subtract 1 from the month; Calendar already knows that it's zero-based.
It seems to me like you're doing far too much work here. Why can't you just do this?
private static final DateFormat DEFAULT_DATE_FORMAT;
static {
DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
DEFAULT_DATE_FORMAT.setLenient(false);
}
public Calendar getCalendar(String dateAsString) {
Calendar value = Calendar.getInstance();
Date d = DEFAULT_DATE_FORMAT.parse(dateAsString);
value.setTime(d);
return value;
}
There's an exception that needs to be added to the method signature, but you get the idea. Look at the Calendar javadocs. This could be easier.
setting a condition to check the month can resolve your problem:
try {
Date fromDt =(Date)df.parse("20131209");
start.setTime(fromDt);
start.set(Calendar.MONTH,(start.get(Calendar.MONTH)));
int month = start.get((Calendar.MONTH));
if (month ==11){
System.out.println(start.get(Calendar.YEAR));
System.out.println(start.get(Calendar.MONTH)+1);
System.out.println(start.get(Calendar.DAY_OF_MONTH));
}else{
start.set(Calendar.MONTH,(start.get(Calendar.MONTH))+1);
System.out.println(start.get(Calendar.YEAR));
System.out.println(start.get(Calendar.MONTH));
System.out.println(start.get(Calendar.DAY_OF_MONTH));
}
}
this will print out :
2013
12
9