Java Date Validation Issue - java

Here is the validation code for Date of format MM/dd/yyyy.
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
formatter.setLenient(false);
Calendar cal = Calendar.getInstance();
Date myDate = formatter.parse("01/02/2014888");
cal.setTime(myDate);
When the date string is 01/02/2014888, it passes the validation.
How can I make the validation correctly?

The Calendar class will allow you to create dates in the future, so 2014888 is a perfectly valid year, albeit a ways off. If you want to add additional constraints to the allowable date, you will need to check the values yourself, such as:
if (cal.get(Calendar.YEAR) > endOfTime) {
// do something about it
}

Related

Time String to time representation Java

I have a string like this 210115 I want to represent it as 21:01:15 any ideas?.
I tried using Gregorian calendar but it adds date to it which I don't want
SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
Date date = new Date();
try{
date = sdf.parse("210115");
}
catch(Exception e){
}
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(date);
System.out.print(calendar.getTime());
Output is Thu Jan 01 21:01:15 UTC 1970 but what I want is just 21:01:15
Thanks.
To output a formatted date, you use another SimpleDateFormat object with a pattern with the format you want.
In this case, it sounds like you might want to use something like
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm:ss");
System.out.println( outputFormat.format(date) );
So what you want is just a time, without time zone. I would recommend using the LocalTime class, which is exactly that, instead of the Date class.
LocalTime time = LocalTime.parse("210115", DateTimeFormatter.ofPattern("HHmmss"));
If u r getting the date string in "210115" this format and you want it in "21:01:15" format then why are you using date format.
Simply do string operation as:
String time="210115";
String newtime=time.substring(0,2)+":"+time.substring(2,4)+":"+time.substring(4,6);
System.out.println(newtime);
you will get the required format.21:01:15

Typecast sql.date to calendar

I have some code that uses the sql.date object to get the current date in the format: yyyy-MM-dd. I want to typecast that to a Calendar object that has the same format as the sql.date.
Here is the code for the sql.date:
java.util.Date now = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date( now.getTime() );
Edit:
I want to know how to put this in a Calendar object. Is it even possible to do this?
A java.sql.Date doesn't have a format. It's just a date.
To convert it to a string, use a SimpleDateFormatter with the relevant format set - or just use toString if you definitely want yyyy-MM-dd. (Unfortunately it's unclear which time zone you should use - java.sql.Date is very poorly documented in this respect. I suspect it will use the default system time zone.)
To create a Calendar object with the given date, you can just use:
Calendar calendar = Calendar.getInstance();
calendar.setTime(sqlDate);
Again, a Calendar doesn't have a text format either - it represents a point in time in a particular calendar system in a particular time zone, but nothing about a textual representation.
Use SimpleDateFormat#format()
System.out.println(new SimpleDateFormat("yyyy-MM-dd")
.format(Calendar.getInstance().getTime()));
Java Date objects (and note that java.sql.Date is a java.util.Date) don't have "formats". They represent an instant in time.
Calendar also doesn't have a "format".
What you're asking for doesn't make sense in java.
Consider using SimpleDateFormat to format one of these things into a String:
String str = new SimpleDateFormat("yyyy-MM-dd").format(myDate);
or if you use a Calendar object (not recommended):
String str = new SimpleDateFormat("yyyy-MM-dd").format(myCalendar.getTime());
You can use the following snippet.
public class DateTest {
public static void main(String[] arg){
Calendar calendar = Calendar.getInstance();
//setting a valid date
Date date = new Date(113,07,10);
//prints the date as per format
System.out.println("Date in YYYY-MM-DD : " +date);
//sets the calendar with the date value in java.sql.Date instance
calendar.setTime(date);
//use simple date formatter to format the value in calendar instance
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Date formatted from Calendar instance : "+dateFormat.format(calendar.getTime()));
}
}
Please let me know what happens!

How to reduce one month from current date and stored in date variable using java?

How to reduce one month from current date and want to sore in java.util.Date variable
im using this code but it's shows error in 2nd line
java.util.Date da = new Date();
da.add(Calendar.MONTH, -1); //error
How to store this date in java.util.Date variable?
Use Calendar:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
Date result = cal.getTime();
Starting from Java 8, the suggested way is to use the Date-Time API rather than Calendar.
If you want a Date object to be returned:
Date date = Date.from(ZonedDateTime.now().minusMonths(1).toInstant());
If you don't need exactly a Date object, you can use the classes directly, provided by the package, even to get dates in other time-zones:
ZonedDateTime dateInUTC = ZonedDateTime.now(ZoneId.of("Pacific/Auckland")).minusMonths(1);
Calendar calNow = Calendar.getInstance()
// adding -1 month
calNow.add(Calendar.MONTH, -1);
// fetching updated time
Date dateBeforeAMonth = calNow.getTime();
you can use Calendar
java.util.Date da = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(da);
cal.add(Calendar.MONTH, -1);
da = cal.getTime();
Using new java.time package in Java8 and Java9
import java.time.LocalDate;
LocalDate mydate = LocalDate.now(); // Or whatever you want
mydate = mydate.minusMonths(1);
The advantage to using this method is that you avoid all the issues about varying month lengths and have more flexibility in adjusting dates and ranges. The Local part also is Timezone smart so it's easy to convert between them.
As an aside, using java.time you can also get the day of the week, day of the month, all days up to the last of the month, all days up to a certain day of the week, etc.
mydate.plusMonths(1);
mydate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)).getDayOfMonth();
mydate.with(TemporalAdjusters.lastDayOfMonth());
Using JodaTime :
Date date = new DateTime().minusMonths(1).toDate();
JodaTime provides a convenient API for date manipulation.
Note that similar Date API will be introduced in JDK8 with the JSR310.
You can also use the DateUtils from apache common. The library also supports adding Hour, Minute, etc.
Date date = DateUtils.addMonths(new Date(), -1)
raduce 1 month of JDF
Date dateTo = new SimpleDateFormat("yyyy/MM/dd").parse(jdfMeTo.getJulianDate());
Calendar cal = Calendar.getInstance();
cal.setTime(dateTo);
cal.add(Calendar.MONTH, -1);
Date dateOf = cal.getTime();
Log.i("dateOf", dateOf.getTime() + "");
jdfMeOf.setJulianDate(cal.get(Calendar.DAY_OF_YEAR), cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.DAY_OF_WEEK_IN_MONTH));

Specify the date format in XMLGregorianCalendar

I want to use a Date in XMLGregorianCalendar format for sending to a web service. The web service expects information in yyyy-dd-mm format. I use the below code to create an XMLGregorianCalendar and send it to web service.
Date dob = null;
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
try {
XMLGregorianCalendar date2;
dob = df.parse("13/06/1983");
GregorianCalendar c = new GregorianCalendar();
c.setTimeInMillis(dob.getTime());
date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
System.out.println(date2);
}
catch(DatatypeConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Unfortunately I always get the date as 1983-06-13T00:00:00.000-04:00. Time is also getting included in the output. Is it possible to get only the date? Could you please help me?
you don't need to specify a "SimpleDateFormat", it's simple:
You must do specify the constant "DatatypeConstants.FIELD_UNDEFINED" where you don't want to show
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date());
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED);
Much simpler using only SimpleDateFormat, without passing all the parameters individual:
String FORMATER = "yyyy-MM-dd'T'HH:mm:ss'Z'";
DateFormat format = new SimpleDateFormat(FORMATER);
Date date = new Date();
XMLGregorianCalendar gDateFormatted =
DatatypeFactory.newInstance().newXMLGregorianCalendar(format.format(date));
Full example here.
Note: This is working only to remove the last 2 fields: milliseconds and timezone or to remove the entire time component using formatter yyyy-MM-dd.
Yeah Got it...
Date dob=null;
DateFormat df=new SimpleDateFormat("dd/MM/yyyy");
dob=df.parse( "13/06/1983" );
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(dob);
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED);
This will give it in correct format.
This is an easy way for any format. Just change it to required format string
XMLGregorianCalendar gregFmt = DatatypeFactory.newInstance().newXMLGregorianCalendar(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date()));
System.out.println(gregFmt);
There isn’t really an ideal conversion, but I would like to supply a couple of options.
java.time
First, you should use LocalDate from java.time, the modern Java date and time API, for parsing and holding your date. Avoid Date and SimpleDateFormat since they have design problems and also are long outdated. The latter in particular is notoriously troublesome.
DateTimeFormatter originalDateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
String dateString = "13/06/1983";
LocalDate date = LocalDate.parse(dateString, originalDateFormatter);
System.out.println(date);
The output is:
1983-06-13
Do you need to go any further? LocalDate.toString() produces the format you asked about.
Format and parse
Assuming that you do require an XMLGregorianCalendar the first and easy option for converting is:
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(date.toString());
System.out.println(xmlDate);
1983-06-13
Formatting to a string and parsing it back feels like a waste to me, but as I said, it’s easy and I don’t think that there are any surprises about the result being as expected.
Pass year, month and day of month individually
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
.newXMLGregorianCalendarDate(date.getYear(), date.getMonthValue(),
date.getDayOfMonth(), DatatypeConstants.FIELD_UNDEFINED);
The result is the same as before. We need to make explicit that we don’t want a time zone offset (this is what DatatypeConstants.FIELD_UNDEFINED specifies). In case someone is wondering, both LocalDate and XMLGregorianCalendar number months the way humans do, so there is no adding or subtracting 1.
Convert through GregorianCalendar
I only show you this option because I somehow consider it the official way: convert LocalDate to ZonedDateTime, then to GregorianCalendar and finally to XMLGregorianCalendar.
ZonedDateTime dateTime = date.atStartOfDay(ZoneOffset.UTC);
GregorianCalendar gregCal = GregorianCalendar.from(dateTime);
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(gregCal);
xmlDate.setTime(DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED,
DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED);
xmlDate.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
I like the conversion itself since we neither need to use strings nor need to pass individual fields (with care to do it in the right order). What I don’t like is that we have to pass a time of day and a time zone offset and then wipe out those fields manually afterwards.

How to convert Formatted Date (yyyy-MM-dd) to Unix time in Java?

How to convert Formatted date (yyyy-MM-dd) to Unix time in Java?
I want to declare a date using
Date birthday = new Date(y_birthday, m_birthday, d_birthday);
but this constructor has been deprecated, so I got to use the other constructor which uses Unix timestamp
So, you have the date as a string in the format yyyy-MM-dd? Use a java.text.SimpleDateFormat to parse it into a java.util.Date object:
String text = "2011-12-12";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date date = df.parse(text);
edit If you need a java.sql.Date, then you can easily convert your java.util.Date to a java.sql.Date:
java.sql.Date date2 = new java.sql.Date(date.getTime());
Use a calendar object if you want more control of the date object
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2011);
calendar.set(Calendar.MONTH, 11); // indexed month (December)
calendar.set(Calendar.DATE, 12);
Date date = new Date(calendar.getTime().getTime());
The hours, minutes, seconds etc of the current time will be set though so you may want to set those to 0 (manually per field)
If you're using Java 7 then I think there's some much nicer stuff you can use for handling dates

Categories