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)
Related
This question already has answers here:
Android/Java - Date Difference in days
(18 answers)
Closed 6 years ago.
I need to calculate number of days between two dates and I am using below code. problem is it is returning me 2 but actually it should return 3 because difference between 30 june 2016 to 27 june is 3. can you please help where it should include current date as well in difference?
public static long getNoOfDaysBtwnDates(String expiryDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
long diff = 0;
long noOfDays = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Date createdDate = new Date();
diff = expDate.getTime() - createdDate.getTime();
noOfDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
long a = TimeUnit.DAYS.toDays(noOfDays);
// logger.info("No of Day after difference are - " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
System.out.println(a);
System.out.println(noOfDays);
} catch (ParseException e) {
e.printStackTrace();
}
return noOfDays;
}
expiry date is 2016-06-30 and current date is 2016-06-27
Reason is, you are not subtracting two dates with same time format.
Use Calendar class to change the time as 00:00:00 for both date and you will get exact difference in days.
Date createdDate = new Date();
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 0);
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
createdDate = time.getTime();
More explaination in Jim Garrison' answer
Why not use LocalDate?
import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.DAYS;
long diffInDays(LocalDate a, LocalDate b) {
return DAYS.between(a, b);
}
The problem is that
Date createdDate = new Date();
sets createdDate to the current instant, that is, it includes the current time as well as the date. When you parse a string using the given format, the time is initialized to 00:00:00.
Let's say you ran this at exactly 18:00 local time, you end up with
createdDate = 2016-06-27 18:00:00.000
expDate = 2016-06-30 00:00:00.000
The difference is 2 days 6 hours, not 3 days.
You should be using the newer java.time.* classes from Java 8. There is a class LocalDate that represents dates without time-of-day. It includes methods for parsing using a format, and LocalDate.now() to get the current date, as well as methods for calculating intervals between LocalDate instances.
Using the Calendar.get(Calendar.DAY_OF_MONTH) as pointed out by python:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
String expiryDate ="2016-06-30";
int diff = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(expDate);
diff = cal.get(Calendar.DAY_OF_MONTH)- today;
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(diff);
This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 7 years ago.
I need to get difference between two dates using Java. I need my result to be in months and year of month.
Example:
Startdate = 2015-04-03 enddate = 2015-05-03 Result should be APR-MAY 2015
Startdate = 2015-12-03 enddate = 2015-01-03 Result should be DEC-2015,JAn-2016
i need to set that value into textview how can i set this plz help me .
String startdate = "2015-11-30";
String enddate = "2016-1-30";
DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
DateFormat outputFormater = new SimpleDateFormat("MMM-yyyy");
Calendar beginCalendar = Calendar.getInstance();
Calendar finishCalendar = Calendar.getInstance();
try {
beginCalendar.setTime(formater.parse(startdate));
finishCalendar.setTime(formater.parse(enddate));
if (beginCalendar.get(Calendar.MONTH) != finishCalendar.get(Calendar.MONTH)){
beginCalendar.set(Calendar.DAY_OF_MONTH, 1);
finishCalendar.set(Calendar.DAY_OF_MONTH, 2);
}
do {
// add one month to date per loop
String month_year = outputFormater.format(beginCalendar.getTime());
Log.d("Date_Range", month_year);
beginCalendar.add(Calendar.MONTH, 1);
} while (beginCalendar.before(finishCalendar));
} catch (ParseException e) {
e.printStackTrace();
}
So by this you will get month and year between start date and end date in MMM-yyyy format. You can handle the result in the way you want by splitting month_year string # "-" separator.
You can use SimpleDateFormat.
EDIT: Try this
SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
Check if your dates are in the same year by getting the year of the calendar.
int year1=Integer.pareInt(formatter.format(calendar1.getTime()));
int year2=Integer.pareInt(formatter.format(calendar2.getTime()));
year=year1-year2;
and then print result based on the year
formatter=new SimpleDateFormat("MMM");
if(year==0)
System.out.println(formatter.format(calendar1)+"-"+formatter.format(calendar2)+" "+ year);
else
System.out.println(formatter.format(calendar1)+"-"+year1+","+formatter.format(calendar2)+"-"+year2);
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();
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
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());
}
}