Using Java SimpleDateFormat to find max date - java

I haven't programmed in Java for many years, but I now have to change a program I wrote some time ago. In this program I need to read a QIF file and find the qif record with the maximum date (Dmm-dd-yyyy).
I could not get this to work in my program so I wrote a simple test to demonstrate the problem I am having. I think there are other ways to do this, like lists and collections. But I still want to know why using SimpleDateFormat won't work. Notice in the output that this method produces the max for July but seems to ignore all August dates.
Thanks, Mike
import java.text.SimpleDateFormat;
import java.util.Date;
class DateParser {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("mm-dd-yyyy");
Date nextDate = null;
Date maxDate = null;
String nextStrDate = null;
String maxStrDate = null;
//Fill date array.
String date[] = {"07-14-2014","07-22-2014","07-31-2014",
"08-01-2014","08-04-2014","08-06-2014"};
try {
//Start with early maximum date.
maxDate = sdf.parse("01-01-1800");
// Find Max date in array.
for (int i=0; i<6; ++i) {
nextStrDate = date[i];
nextDate = sdf.parse(nextStrDate);
if(nextDate.after(maxDate)){
maxStrDate = nextStrDate;
maxDate = nextDate;
}
System.out.println( "Next Date = " + nextStrDate);
}
System.out.println("\nMax Date = " + maxStrDate);
} catch (Exception e) {
System.out.println("Got error:" + e);
}
}
}
OUTPUT
Next Date = 07-14-2014
Next Date = 07-22-2014
Next Date = 07-31-2014
Next Date = 08-01-2014
Next Date = 08-04-2014
Next Date = 08-06-2014
Max Date = 07-31-2014

From the Java Docs....
m Minute in hour
What you want is
M Month in year
Change mm-dd-yyyy to MM-dd-yyyy

You format is incorrect, this
SimpleDateFormat sdf = new SimpleDateFormat("mm-dd-yyyy");
should be
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
because (per the SimpleDateFormat documentation),
Letter Date or Time Component Presentation Examples
...
M Month in year Month July; Jul; 07
...
m Minute in hour Number 30

Related

Convert hour interval to 24h interval

I would like to convert "9:00 am – 11:00 pm" -> "9:00 - 23:00", how can I do that? What I've tried so far:
if(input.contains("am")) { //This because I have a string with other kind of items too (not only these interval of hours but names, etc)
DateFormat df = new SimpleDateFormat("h:mm a – h:mm a");
DateFormat outputformat = new SimpleDateFormat("HH:mm - HH:mm");
Date date = null;
String output = null;
date= df.parse(input);
input = outputformat.format(date);
System.out.println("Output: "+output);
}
but the output is wrong, in the example 23:00 - 23:00 because it doesn't recognize the first and the second hour
I tried also something like:
DateFormat df = new SimpleDateFormat("h:mm a" +" - "+ "h:mm a");
DateFormat outputformat = new SimpleDateFormat("HH:mm"+" - "+ "HH:mm");
but I got a parse error then
Try this:
String dateToParse = "9:00 am – 11:00 pm";
String splitDate[] = dateToParse.split("–");
DateFormat df = new SimpleDateFormat("h:mm a");
DateFormat outputformat = new SimpleDateFormat("HH:mm");
Date date1 = null, date2 = null;
String output1 = null, output2 = null;
try {
date1 = df.parse(splitDate[0].trim());
date2 = df.parse(splitDate[1].trim());
} catch (ParseException e) {
e.printStackTrace();
}
output1 = outputformat.format(date1);
output2 = outputformat.format(date2);
System.out.println("Output: " + output1 + " – " + output2);
Go object-oriented and use java.time
Don’t convert your interval from one string format to another. Design an Interval class for storing and manipulating your time intervals. I suggest that you include a convenience constructor that accepts a string and a toString method that produces your desired format.
I furthermore recommend that you use java.time, the modern Java date and time API, for your time work.
public class Interval {
private static final String middlePart = " – ";
private static final DateTimeFormatter amPmFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("h:mm a")
.toFormatter(Locale.ENGLISH);
private LocalTime begin;
private LocalTime end;
public Interval(String intervalString) {
String[] timeStrings = intervalString.split(middlePart);
if (timeStrings.length != 2) {
throw new IllegalArgumentException("Improper format");
}
begin = LocalTime.parse(timeStrings[0], amPmFormatter);
end = LocalTime.parse(timeStrings[1], amPmFormatter);
}
#Override
public String toString() {
return "" + begin + middlePart + end;
}
}
To try it out:
Interval testInterval = new Interval("9:00 am – 11:00 pm");
System.out.println(testInterval);
Output is:
09:00 – 23:00
What went wrong in your code?
Date is the completely wrong class to use for your interval. The class is poorly designed and long outdated. A date represents a point in time, not a time of day and certainly not an interval of two times of day.
SimpleDateFormat — a notorious troublemaker of a class — tried to parse your string into a time of January 1, 1970 in your time zone. It should have objected because a time on that day cannot be both 9 AM and 11 PM — you were contradicting yourself. But no, SimpleDateFormat gives you one of those times, keeps its mouth shut and pretends all is well. Possibly an attempt to be nice, but if so, IMHO a completely misunderstood attempt.
Link
Oracle tutorial: Date Time explaining how to use java.time.

Finding week number by passing two timestamps as parameter in Java [duplicate]

This question already has answers here:
Get the number of weeks between two Dates.
(19 answers)
Closed 6 years ago.
My function should take start timestamp, end timestamp and entered date. Here, start and end timestamps could be anything (any timestamp).
This start timestamp and end timestamp will be of three week. If entered date falls in those timestamp range I need to get week of that date.
example:
start date - 06/08/2011 00:00:00
end Date - 26/08/2011 00:00:00
if entered date - 10/08/2011 This should return week number as 1
if entered date - 27/08/2011 This should return week number as 3.it has to take count of 7 days,from entered date and give the count of week.
Below is my code used.
import java.util.Calendar;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class LocaleTimeSample {
public static void main(String... args) {
try {
String dt = "";
String dt1 = "";
String dt2 = "";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
sdf.setLenient(false);
String givenDateString = "02/06/2016";// given
String startDateString = "01/06/2016";// start
String endDateString = "21/06/2016";// end
Date givenDate = sdf.parse(givenDateString);
Date startDate = sdf.parse(startDateString);
Date endDate = sdf.parse(endDateString);
try {
c.setTime(sdf.parse(startDateString));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.add(Calendar.DAY_OF_MONTH, 7); // number of days to add
dt = sdf.format(c.getTime());
System.out.println("1 Week Date : " + dt);
Date date1 = (Date) sdf.parse(dt);
c.add(Calendar.DAY_OF_MONTH, 7); // number of days to add
dt1 = sdf.format(c.getTime());
System.out.println("2 Week Date : " + dt1);
Date date2 = (Date) sdf.parse(dt1);
c.add(Calendar.DAY_OF_MONTH, 7); // number of days to add
dt2 = sdf.format(c.getTime());
System.out.println("2 Week Date : " + dt2);
Date date3 = (Date) sdf.parse(dt2);
if (givenDate.compareTo(date1) <= 0) {
System.out.println("Week 1");
} else if (givenDate.compareTo(date2) <= 0
&& givenDate.compareTo(date1) > 0) {
System.out.println("Week 2");
} else if (givenDate.compareTo(date3) <= 0
&& givenDate.compareTo(date2) > 0) {
System.out.println("Week 3");
}
} catch (ParseException pe) {
pe.printStackTrace();
}
}
}
Can anybody help me to minimixe the code of line and reusability apprach where were needed.
Any idea regarding this is appreciated.
Convert to Date or Calendar and retreive the field you need
Assumming your Date is String this is what you must do to convert it to Date and Calendar
String startDate = "06/08/2011 00:00:00";
DateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date startDateasDate = format.parse(startDate);
Calendar cal = Calendar.getInstance();
cal.setTime(startDateasDate);
Then you can retrieve wichever date you want with the proper flag:
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
int weekOfYear = cal.get(Calendar.WEEK_OF_YEAR);
Here you can see a list of the available flags:
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
Convert the start date, end date and input date to LocalDateTime
Check that the entered date is after the start date and before the end date. You can use LocalDateTime.isBefore and isAfter for this.
Use LocalDateTime.until with TemporalUnit set to weeks to calculate the amount of weeks from the start date to the entered date. You can then add 1 to this result to get the week number (0 amount of weeks = week 1, 1 amount of weeks = week 2 and so on)

Only accept two or four digit years from users

I have to accept a date from a user via a simple inputText field (JSF 2). I created a Converter so I can validate the date and now I am running into trouble with 1, 3, and 5+ digit years. All dates entered by the user will be either today or in the future (up to a reasonable maximum).
The below solution accepts three different date formats and will correctly handle 2 and 4 digit years (in the former case by using set2DigitYearStart to convert them to 20XX). I am completely stumped how I can handle other wrong dates.
Code
public static void main(String[] args) throws Exception {
String date = "2/3/111"; // This should be rejected!
List<String> datePatterns = new ArrayList<String>();
datePatterns.add("MM-dd-yy");
datePatterns.add("MM.dd.yy");
datePatterns.add("MM/dd/yy");
for (String pattern : datePatterns) {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
formatter.set2DigitYearStart(new SimpleDateFormat("MM/dd/yyyy").parse("1/1/2000"));
formatter.setLenient(false);
try {
System.out.println(formatter.parse(date));
break;
} catch (ParseException ignore) {
System.out.println("Date format doesn't match pattern: " + pattern);
}
}
}
Examples That Should be Accepted
02/02/02
02/02/2002
Examples That Should be Rejected
02/02/1
02/02/333
02/02/55555
One Approach
Get some theoretical maxDate and yesterday's date, then compare the output. This seems wrong somehow, though...
SimpleDateFormat f4 = new SimpleDateFormat("MM/dd/yyyy");
Date maxDate = f4.parse("01/01/2099");
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
Date minDate = f4.parse(dateFormat.format(cal.getTime()));
Add some specific validation after your parsing is finished to reject any years that are out of range ie getYear() < 1000 and getYear() > 9999
Warning this code is not compiled or tested as I am typing on a tablet.
String dateStr = "2/3/111"; // This should be rejected!
List<String> datePatterns = new ArrayList<String>();
datePatterns.add("MM-dd-yy");
datePatterns.add("MM.dd.yy");
datePatterns.add("MM/dd/yy");
Date date = null;
for (String pattern : datePatterns) {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
formatter.set2DigitYearStart(new SimpleDateFormat("MM/dd/yyyy").parse("1/1/2000"));
formatter.setLenient(false);
try {
date = dateformatter.parse(dateStr));
break;
} catch (ParseException ignore) {
continue;
}
}
if (date != null) {
Calendar cal = new GregorianCalendar (date);
int year = cal.get(Calendar.YEAR);
if (year() < 1000 || year() > 9999) {
System.out.println("Date format doesn't match pattern: "
+ datePatterns);
}
} else {
System.out.println("Date format doesn't match pattern: "
+ datePatterns);
{

Java date displays previous day , month and totally different year

I am trying to display Date based on timezone.
If I change my system time zone to US pacific time zone, today's date is displayed correctly. If I want to display 2000-01-01 output shows as 12/31/1969.
Can you please let me know if I have to make any change in system settings or java settings?.
Below is the example code:
package timezoneexample;
import java.text.DateFormat;
import java.util.Date;
import java.util.TimeZone;
public class TimezoneExample {
public static void main(String args[]) {
DateFormat dateFormat = null;
String datePattern = null;
char dateSeperator = '/';
try {
datePattern = "MM/dd/yyyy";
if (datePattern.length() <= 0)
throw new java.util.MissingResourceException(
"Didn't find date format", "", "");
boolean hasSeperatorAlready = false;
for (int i = 0; i < datePattern.length(); i++)
if (!Character.isLetter(datePattern.charAt(i)))
if (hasSeperatorAlready)
throw new java.util.MissingResourceException(
"Unvalid date format", "", "");
else
dateSeperator = datePattern.charAt(i);
} catch (java.util.MissingResourceException mre) {
System.out.println(mre);
}
dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
if (datePattern.length() > 0
&& dateFormat instanceof java.text.SimpleDateFormat) {
java.text.SimpleDateFormat sdf = (java.text.SimpleDateFormat) dateFormat;
sdf.applyPattern(datePattern);
}
dateFormat.setTimeZone(java.util.TimeZone.getDefault());
// enter DOB
Date dob = new Date(2000 - 01 - 01);
Date today = new Date();
String timeZone = System.getProperties().getProperty("user.timezone");
TimeZone tZone = TimeZone.getTimeZone(timeZone);
System.out.println("Timezone : " + tZone);
dateFormat.setTimeZone(tZone);
System.out.println("Date Of Birth : " + dateFormat.format(dob));
System.out.println("Date in Displayed as per Timezone : "
+ dateFormat.format(today));
}
}
Output:
Timezone : sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]]
Date Of Birth : 12/31/1969
Date in Displayed as per Timezone : 01/07/2015
Your error is here:
Date dob = new Date(2000 - 01 - 01);
This will be interpreted as:
Date dob = new Date(1998);
This will invoke the Date(long date) constructor, resulting in a date near 1970/01/01.
What you most probably want is:
Date dob = new Date(2000, 1, 1);
new Date(...) requires a long value, expressing the number of milliseconds since 1/1/1970. You're specifying 2000 - 1 - 1. This is NOT "year 2000, month 1 and day 1", it is a numeric expression equal to 1998 milliseconds.
To create a date based on year/month/day, use a Calendar:
Calendar c = Calendar.getInstance();
c.set(y, m-1 /* 0-based */, d); // e.g. c.set(2000, 0, 1);
return c.getTime();

Date function in java

I have two dates
1) from_date: eg. 01/01/2010 (1st January 2010)
2) present_date: eg. 05/06/2011 (5th June 2011)
I want the third date as:
3) req_date: eg. 01/01/2011(1st January 2011)
Year should come from "present_date" and day and month should come from "from_date".
The dates which I mentioned are hardCoded.
In my code, I run a query to get these 2 dates.
Look into the Calendar class
http://www.java-examples.com/add-or-substract-days-current-date-using-java-calendar
Something like // Untested
Calendar cal=Calendar.getInstance();
cal.setTime(from_date);
Calendar cal2=Calendar.getInstance();
cal2.setTime(present_date);
Calendar cal3=Calendar.getInstance();
cal3.set(cal2.get(CALENDAR.YEAR),cal1.get(CALENDAR.MONTH),cal1.get(CALENDAR.DATE));
Date reg_date = cal3.getTime();
You can set individual fields of dates:
Date req_date = from_date;
req_date.setYear (present_date.getYear());
Or, if you're using Calendar (Date is deprecated):
Calendar req_date = from_date;
req_date.set (YEAR, present_date.get(YEAR));
If they're strings, you can just use substringing to get what you want:
String req_date = from_date.substring(0,6) + present_date.substring(6);
(assuming XX/XX/YYYY as seems to be the case).
Not sure if I understand you correctly but this example should get you started:
int year = 2003;
int month = 12;
int day = 12;
String date = year + "/" + month + "/" + day;
java.util.Date utilDate = null;
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
utilDate = formatter.parse(date);
System.out.println("utilDate:" + utilDate);
} catch (ParseException e) {
System.out.println(e.toString());
e.printStackTrace();
}
this way you can convert date Strings to java.util.Date object, then you can construct the third date by using Date/Calendar methods
from_date: for EX. 01/01/2010 (1 st January 2010)
present_date :for EX. 05/06/2011(5th june 2011)
String s1[]=from_date.split("/");
String s2[]=present_date.split("/");
String newDate=s1[0]+"/"+s1[1]+"/"+s2[2];
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
Date date = new Date();
System.out.println(date.toString());
}
}

Categories

Resources