This question already has answers here:
Why dec 31 2010 returns 1 as week of year?
(6 answers)
Closed 5 years ago.
I implemented the following method:
private int getWeek(String datum){
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
Date date = null;
try {
date = format.parse(datum);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone( "Europe/Berlin" ));
calendar.setTime(date);
int week = calendar.get(Calendar.WEEK_OF_YEAR);
return week;
}
But when I call the method with
getWeek("01.01.2017")
it returns 52. But it should be 1.
Where is my mistake?
When i call the method with
getWeek("01.01.2016")
it returns 53.
you have lost set the TimeZone in SimpleDateFormat, for example:
private int getWeek(String datum) {
TimeZone zone = TimeZone.getTimeZone("Europe/Berlin");
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
// v--- set the timezone here
format.setTimeZone(zone);
Date date = null;
try {
date = format.parse(datum);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance(zone);
calendar.setTime(date);
int week = calendar.get(Calendar.WEEK_OF_YEAR);
return week;
}
Damnit.. that was a huge brain failure.
52 is the correct answer for the input.
in Germany the first Week of Year is the first week with 4 or more days in the new year.
Sorry.
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:
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)
This question already has answers here:
Convert a date format in epoch
(6 answers)
Closed 6 years ago.
Is there a way to convert a given Date String into Milliseconds (Epoch Long format) in java? Example : I want to convert
public static final String date = "04/28/2016";
into milliseconds (epoch).
The getTime() method of the Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
You can simply parse it to java.util.Date using java.text.SimpleDateFormat and call it's getTime() function. It will return the number of milliseconds since Jan 01 1970.
public static final String strDate = "04/28/2016";
try {
Long millis = new SimpleDateFormat("MM/dd/yyyy").parse(strDate).getTime();
} catch (ParseException e) {
e.printStackTrace();
}
You can create a Calendar object and then set it's date to the date you want and then call its getTimeInMillis() method.
Calendar c = new Calendar.getInstance();
c.set(2016, 3, 28);
c.getTimeInMillis();
If you want to convert the String directly into the date you can try this:
String date = "4/28/2016";
String[] dateSplit = date.split("/");
c.set(Integer.valueOf(dateSplit[2]), Integer.valueOf(dateSplit[0]) - 1, Integer.valueOf(dateSplit[1]));
c.getTimeInMillis();
You will need to use Calendar instance for getting millisecond from epoch
try {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
java.util.Date d = sdf.parse("04/28/2016");
/*
* Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
*/
System.out.println(d.getTime());
//OR
Calendar cal = Calendar.getInstance();
cal.set(2016, 3, 28);
//the current time as UTC milliseconds from the epoch.
System.out.println(cal.getTimeInMillis());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This question already has an answer here:
SimpleDateFormat("dd-MMM-YYYY") printing year one year ahead [duplicate]
(1 answer)
Closed 6 years ago.
I run the following code and obtain incorrect date (instead of 1/2/2015 6:00:00 AM it prints 12/28/2015 6:00:00 AM):
SimpleDateFormat _sdf = new SimpleDateFormat("M/d/YYYY H:mm:ss a");
_time = "02/01/2015 6:00:00 AM";
Date date;
try {
date = _sdf.parse(_time);
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(date);
_time = _sdf.format(calendar.getTime());
System.out.println(_time); // 12/28/2015 6:00:00 AM !!!
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try to use this:
SimpleDateFormat _sdf = new SimpleDateFormat("M/d/yyyy H:mm:ss a");
i.e, you need to use yyyy instead if YYYY.
Check the Oracle Docs
y Year Year 1996; 96
Y Week year Year 2009; 09
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);