I use the following code to check the consistency between joda's DateTime and java.util.Calendar. This result is correct, but if I change the year 2000 to 1900, then I will get 2 different result. Is this a bug or something else cause this ?
Calendar c = Calendar.getInstance();
c.set(1900,0,1,0,0,0); // Calendar's month is 0 based
c.set(Calendar.MILLISECOND, 0);
System.out.println(c.getTimeInMillis() / 1000);
DateTime dt = new DateTime(1900,1,1,0,0,0); // joda's month is 1 based
System.out.println(dt.getMillis() / 1000);
And this is the output
-2209017600
-2209017943
It's something else :)
import org.joda.time.DateTime;
import java.util.Calendar;
public class DateTester {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
c.set(1900,0,1,0,0,0);
c.set(Calendar.MILLISECOND, 0);
System.out.println(c.getTimeInMillis()/1000);
DateTime dt = new DateTime(1900,1,1,0,0,0);
System.out.println(dt.getMillis()/1000);
}
}
result:
-2208992400
-2208992400
Process finished with exit code 0
It has to do with offset between UTC and your timezone. For my timezone it is 1893
import org.joda.time.DateTime;
import java.util.Calendar;
public class DateTester {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
int i = 1900;
boolean found = false;
while (!found) {
c.set(i,0,1,0,0,0);
c.set(Calendar.MILLISECOND, 0);
DateTime dt = new DateTime(i,1,1,0,0,0);
found = !(c.getTimeInMillis() == dt.getMillis());
if (found) {
System.out.println("year: " + i);
System.out.println(c.getTimeInMillis());
System.out.println(dt.getMillis());
}
i--;
}
}
}
Result:
year: 1893
-2429830800000
-2429830408000
This offset between UTC and set time-zone can be checked in time zone data base
Related
I have to create a program which prints out a list of dates (year, month, days) until a users selected date (end_date which is later converted to end_cal).
For example, if today is 2017-09-30 Saturday and user inputs date 2017-10-30, program must print out these dates:
2017-09-30, 2017-10-07, 2017-10-14, 2017-10-21, 2017-10-28.
Problems:
Adding calendar type elements into a list
Printing the list.
Formatting dates during printing of addition to the list
When I try to print it, output is just a bunch of duplicates of same date.
public class Weekdays {
static Scanner input = new Scanner(System.in);
static Calendar temp_cal = Calendar.getInstance(); //temporary calendar object. it's value is being chaged in the process
static Calendar start_cal = Calendar.getInstance(); // current day when the program is executed
static Calendar end_cal = Calendar.getInstance(); //end date that the user inputs
static SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
public static boolean date_validation(String date){ //partial validation: whether the input date is in a correct format
Date test_date;
try {
test_date = format.parse(date);
}catch (ParseException e){
return false;
}
return true;
}
//created list of dates that are of the same day of the week (for example all Sundays)
static private List<Calendar> getListOfDates(){
List<Calendar> dates = new ArrayList<>();
while (!((temp_cal.get(Calendar.YEAR)>= end_cal.get(Calendar.YEAR))&&(temp_cal.get(Calendar.MONTH) >= end_cal.get(Calendar.MONTH))&&(temp_cal.get(Calendar.DAY_OF_YEAR) >= end_cal.get(Calendar.DAY_OF_YEAR))))
{
temp_cal.add(Calendar.DATE, 7);
dates.add(temp_cal); }
return dates;
}
static private void printListOfDates(List<Calendar> dates){
System.out.println(Arrays.toString(dates.toArray()));
}
public static void main(String[] str) throws ParseException{
String end_date = input.next();
while(!(date_validation(end_date))){
end_date = input.next();
}
end_cal.setTime(format.parse(end_date));
printListOfDates(getListOfDates());
}
Input: 2018/01/01
Output (copied only one example, whole output is just several duplicates of this):
java.util.GregorianCalendar[time=1515233525518,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Helsinki",offset=7200000,dstSavings=3600000,useDaylight=true,transitions=118,lastRule=java.util.SimpleTimeZone[id=Europe/Helsinki,offset=7200000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2018,MONTH=0,WEEK_OF_YEAR=1,WEEK_OF_MONTH=1,DAY_OF_MONTH=6,DAY_OF_YEAR=6,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=0,HOUR_OF_DAY=12,MINUTE=12,SECOND=5,MILLISECOND=518,ZONE_OFFSET=7200000,DST_OFFSET=0]]
I'm not sure if this is the correct format for you (I will leave that as a task for you) but you could do something like this using LocalDate:
import java.util.Scanner;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate endDate;
while(true){
System.out.print("Enter the endDate in the format of yyyy/MM/dd:");
String date = scanner.next();
try {
endDate = LocalDate.parse(date, formatter);
break;
} catch (Exception e) {
System.err.println("ERROR: Please input the date in the correct format");
}
}
System.out.println("Below are the days between the current day and " + endDate);
printDaysBetween(endDate);
}
public static void printDaysBetween(LocalDate end){
LocalDate start = LocalDate.now();
while (!start.isAfter(end)) {
System.out.println(start);
start = start.plusDays(7);
}
}
}
Example Usage:
Enter the endDate in the format of yyyy/MM/dd: 2017-10-30
ERROR: Please input the date in the correct format
Enter the endDate in the format of yyyy/MM/dd: 2017/10/30
Below are the days between the current day and 2017-10-30
2017-09-30
2017-10-07
2017-10-14
2017-10-21
2017-10-28
The first issue is with the way you print out the result:
System.out.println(Arrays.toString(dates.toArray()));
If you want formatted dates, you will need to make use of a formatter.
private static SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
static private void printListOfDates(List<Calendar> dates){
for (Calendar date : dates) {
System.out.println(outputFormat.format(date));
}
}
A second issue is that you seem to reuse the same temp_cal object in your loop in getListOfDates. This results in your list containing multiple copies of the same Calendar object (which is modified multiple times). You will need to create a new instance for every iteration in your loop.
import java.util.Date;
import java.time.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class days
{
public static void main (String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter Dates (Start(yyyy/mm/dd)-End)");
//example 2017 1 5 -> 5 jan 2017
getDates(Integer.parseInt(input.next()),Integer.parseInt(input.next()),
Integer.parseInt(input.next()),Integer.parseInt(input.next()),
Integer.parseInt(input.next()),Integer.parseInt(input.next()));
/*the input needed example
* 2017
* 1
* 1 -Start date
* 2017
* 2
* 10 -End date
*/
}
public static void getDates(int pYearStart, int pMonthStart, int pDayStart,
int pYearEnd, int pMonthEnd, int pDayEnd){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd");
int year = pYearStart;
int month = pMonthStart-1;
int day = pDayStart;
Calendar start = new GregorianCalendar(year,month,day);
int yearEnd = pYearEnd;
int monthEnd = pMonthEnd-1;
int dayEnd = pDayEnd;
Calendar end = new GregorianCalendar(yearEnd,monthEnd,dayEnd);
System.out.print("Start Date: ");
System.out.println(sdf.format(start.getTime()));
System.out.print("End Date: ");
System.out.println(sdf.format(end.getTime()));
System.out.println("");
System.out.println("All Dates:");
boolean sameDate = false;
int amount = 0;
do{
System.out.println(sdf.format(start.getTime()));
start.add(Calendar.DAY_OF_MONTH, 7);
amount++;
if(start.get(Calendar.DAY_OF_MONTH) >= end.get(Calendar.DAY_OF_MONTH) &&
start.get(Calendar.MONTH) == end.get(Calendar.MONTH)) {
sameDate = true;}
}while(sameDate != true);
System.out.println("No of dates: "+amount);
}
}
I think this is what you wanted, I didnt use a list but change it as you like.
This question already has answers here:
How to get last month/year in java?
(10 answers)
Closed 7 years ago.
First i set month and year then i want previous month and year not current month. now i getting which month set on calender that month only
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class PrevMonth
{
private static String prev_day_str;
private static String prev_month_str;
public static void main(String[] args)
{
SimpleDateFormat prev_day = new SimpleDateFormat("dd");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, 1);
calendar.set(Calendar.YEAR, 2015);
calendar .add(Calendar.MONTH, -1); //subtracting a month
SimpleDateFormat prev_month = new SimpleDateFormat("MM");
SimpleDateFormat prev_year = new SimpleDateFormat("YYYY");
prev_day_str = prev_month.format(new Date(calendar .getTimeInMillis()));
prev_month_str = prev_year.format(new Date(calendar .getTimeInMillis()));
System.out.println(prev_day_str+" "+prev_month_str);
}
}
Result:
01 2015
need for 12 2014
Your code:
calendar.set(Calendar.MONTH, 1);
actually sets the month to February.
For January you need to use 0, ie.
calendar.set(Calendar.MONTH, 0);
You start by initialize the calendar to February instead of January :
public class PrevMonth {
private static String prev_day_str;
private static String prev_month_str;
public static void main(String[] args)
{
SimpleDateFormat prev_day = new SimpleDateFormat("dd");
Calendar calendar = Calendar.getInstance();
// 0 for January
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.YEAR, 2015);
// -1 for substruct
calendar .add(Calendar.MONTH, -1); //subtracting a month
SimpleDateFormat prev_month = new SimpleDateFormat("MM");
SimpleDateFormat prev_year = new SimpleDateFormat("YYYY");
prev_day_str = prev_month.format(new Date(calendar .getTimeInMillis()));
prev_month_str = prev_year.format(new Date(calendar .getTimeInMillis()));
System.out.println(prev_day_str+" "+prev_month_str);
}
}
I need to get the full days between two dates in java (the dates are given in Date type) .
For example:
01/01/2015/12:00:00 - 01/02/2015/11:59:00 isn't a full day
and i need to consider daylight savings.
I know that jodatime lib does that but i reached the 65k method limit and i cant use jodatime lib.
i tried the millisecond diff way and the while loop that uses the "before" method:
Android/Java - Date Difference in days
I manage to figure it out:
i used some of this code - https://stackoverflow.com/a/28865648/3873513
and added some of mine:
public static int calcDaysDiff(Date day1, Date day2) {
Date d1 = new Date(day1.getTime());
Date d2 = new Date(day2.getTime());
Calendar date1 = Calendar.getInstance();
date1.setTime(d1);
Calendar date2 = Calendar.getInstance();
date2.setTime(d2);
//checks if the start date is later then the end date - gives 0 if it is
if (date1.get(Calendar.YEAR) >= date2.get(Calendar.YEAR)) {
if (date1.get(Calendar.DAY_OF_YEAR) >= date2.get(Calendar.DAY_OF_YEAR)) {
return 0;
}
}
//checks if there is a daylight saving change between the two dates
int offset = calcOffset(d1, d2);
if (date1.get(Calendar.YEAR) > date2.get(Calendar.YEAR)) {
//swap them
Calendar temp = date1;
date1 = date2;
date2 = temp;
}
return calcDaysDiffAux(date1, date2) + checkFullDay(date1, date2, offset);
}
// check if there is a 24 hour diff between the 2 dates including the daylight saving offset
public static int checkFullDay(Calendar day1, Calendar day2, int offset) {
if (day1.get(Calendar.HOUR_OF_DAY) <= day2.get(Calendar.HOUR_OF_DAY) + offset) {
return 0;
}
return -1;
}
// find the number of days between the 2 dates. check only the dates and not the hours
public static int calcDaysDiffAux(final Calendar day1, final Calendar day2) {
Calendar dayOne = (Calendar) day1.clone(),
dayTwo = (Calendar) day2.clone();
if (dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR)) {
return Math.abs(dayOne.get(Calendar.DAY_OF_YEAR) - dayTwo.get(Calendar.DAY_OF_YEAR));
} else {
int extraDays = 0;
while (dayTwo.get(Calendar.YEAR) > dayOne.get(Calendar.YEAR)) {
dayTwo.add(Calendar.YEAR, -1);
// getActualMaximum() important for leap years
extraDays += dayTwo.getActualMaximum(Calendar.DAY_OF_YEAR);
}
return extraDays - day1.get(Calendar.DAY_OF_YEAR) + day2.get(Calendar.DAY_OF_YEAR);
}
}
public class DateDiff {
public static void main(String[] av) {
SimpleDateFormat myFormat = new SimpleDateFormat("MM/dd/yyyy/HH:mm:ss");
String inputString1 = "01/01/2015/12:00:00";
String inputString2 = "01/02/2015/11:59:00";
try {
Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
long diff = date2.getTime() - date1.getTime(); // Calculate the different
int days = (int) (diff / (1000*60*60*24)); // This convert milliseconds to days
System.out.println ("Days differ: " + days);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The following code will calculate the two dates given, the result print is:
Days differ: 0
This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
How can I add business days to the current date in Java?
(14 answers)
Closed 8 years ago.
I want two dates.
1) Current date in MM/dd/yy format
2) Modified date which will be the adition of five business days(Mon-Fri) to current date and it should be in MMM dd, yyyy format.
So if my current is 9th june than currentDate should be 06/09/14 and modifiedDate should be Jun 13, 2014.
How to do this?
This will add working days (Mon-Fri) and will present dates in the required format.
UPDATED 6 Jul 2020
Now custom days can be used as non working days (see the list NON_BUSINESS_DAYS)
Now even the past date can be calculated as well (set businessDays as negative val)
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class BusinessDateExamples {
private static final List<Integer> NON_BUSINESS_DAYS = Arrays.asList(
Calendar.SATURDAY,
Calendar.SUNDAY
);
/**
* Returns past or future business date
* #param date starting date
* #param businessDays number of business days to add/subtract
* <br/>note: set this as negative value to get past date
* #return past or future business date by the number of businessDays value
*/
public static Date businessDaysFrom(Date date, int businessDays) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
for (int i = 0; i < Math.abs(businessDays);) {
// here, all days are added/subtracted
calendar.add(Calendar.DAY_OF_MONTH, businessDays > 0 ? 1 : -1);
// but at the end it goes to the correct week day.
// because i is only increased if it is a week day
if (!NON_BUSINESS_DAYS.contains(calendar.get(Calendar.DAY_OF_WEEK))){
i++;
}
}
return calendar.getTime();
}
public static void main(String...strings) {
SimpleDateFormat s = new SimpleDateFormat("MM/dd/yy ( MMM dd, yyyy )");
Date date = new Date();
int businessDays = 5;
System.out.println(s.format(date));
System.out.print("+ " + businessDays + " Business Days = ");
System.out.println(s.format(businessDaysFrom(date, businessDays)));
System.out.print("- " + businessDays + " Business Days = ");
System.out.println(s.format(businessDaysFrom(date, -1 * businessDays)));
}
}
Date date=new Date();
Calendar calendar = Calendar.getInstance();
date=calendar.getTime();
SimpleDateFormat s;
s=new SimpleDateFormat("MM/dd/yy");
System.out.println(s.format(date));
int days = 5;
for(int i=0;i<days;)
{
calendar.add(Calendar.DAY_OF_MONTH, 1);
//here even sat and sun are added
//but at the end it goes to the correct week day.
//because i is only increased if it is week day
if(calendar.get(Calendar.DAY_OF_WEEK)<=5)
{
i++;
}
}
date=calendar.getTime();
s=new SimpleDateFormat("MMM dd, yyyy");
System.out.println(s.format(date));
Ref : https://stackoverflow.com/a/15339851/3603806
and https://stackoverflow.com/a/11356123/3603806
The notion of working days is not implemented in Java, it's too subject to interpretation (for example, many international companies have their own holidays). Code below uses isWorkingDay(), which only returns false for weekends - add your holidays there.
public class Test {
public static void main(String[] args) {
Calendar cal = new GregorianCalendar();
// cal now contains current date
System.out.println(cal.getTime());
// add the working days
int workingDaysToAdd = 5;
for (int i=0; i<workingDaysToAdd; i++)
do {
cal.add(Calendar.DAY_OF_MONTH, 1);
} while ( ! isWorkingDay(cal));
System.out.println(cal.getTime());
}
private static boolean isWorkingDay(Calendar cal) {
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SUNDAY || dayOfWeek == Calendar.SATURDAY)
return false;
// tests for other holidays here
// ...
return true;
}
}
Here is the code sample to add dates. You may modify in order to you can only add business days.
SimpleDateFormat sdf1 = new SimpleDateFormat("MM/dd/yy");
SimpleDateFormat sdf2 = new SimpleDateFormat("MMM dd, yyyy");
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
System.out.println(sdf1.format(calendar.getTime()));
calendar.add(Calendar.DATE,6);
System.out.println(sdf2.format(calendar.getTime()));
I am able to increment and decrement a date in my blackberry app.
The issue comes when I change some data in popup screen and click on next the date remains the same without incrementing however the long value is same as the incremented value.
Calendar calendar = Calendar.getInstance();
String dateFormat = compareDate; //mar 28,2012-compare date value
String m = dateFormat.substring(0, 3);
String dd = dateFormat.substring(4, 6);
String y = dateFormat.substring(7, 11);
dateFormat = dd + " " + m + " " + y; // 28 mar 2012
long dateLong = HttpDateParser.parse(dateFormat);
long ctimeMinus50Days = dateLong + 1L * ((long) DateTimeUtilities.ONEDAY);
calendar.setTime ( new Date(ctimeMinus50Days) );
System.out.println("ctimeMinus50Days" + ctimeMinus50Days);
Date d = calendar.getTime();
SimpleDateFormat sd1Exactform = new SimpleDateFormat("MMM dd,yyyy");
sd1Exactform.format(d);
if (dateCurrent != null) { //static value so making null before assigning new value
dateCurrent = null;
}
dateCurrent = sd1Exactform.format(d);
ctimeMinus50Days value is same when is works for increment, but when I see dateCurrent output it's the old date only even though long value shows incremented data.
You can use this class
public class DateUtilities {
static Calendar calendar = Calendar.getInstance();
public static long getPreviousDate(long currentDate){
calendar.setTime(new Date(currentDate));
calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - 1);
return calendar.getTime().getTime();
}
public static long getNextDate(long currentDate){
calendar.setTime(new Date(currentDate));
calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
return calendar.getTime().getTime();
}
}
Calendar class exposes add method which you should use to add/subtract date elements. Here's an example to add one day to a date represented by the string:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Test {
public static void main(String[] args) throws Exception{
String dateCurrent = "Mar 1,2012";
SimpleDateFormat sdExactform = new SimpleDateFormat("MMM d,yyyy");
Date date = sdExactform.parse(dateCurrent);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, 1);
System.out.println(calendar.toString());
}
}