This question already has answers here:
How to add n days to a Date in java without importing Date/Calendar from java API?
(8 answers)
Closed 3 years ago.
can i use calender by using parameter like if date 5-6-2018 to 26-9-2018
i'm looking for many solve but i didn't get plz i need help for my homework
don't care about 31 or 30 days or Leap Year just i need how to do it
public Date(int day, int month, int year) {
this.day = day;
this.month=month;
this.year=year;
}
public void setDay(int day) {
this.day = day;
}
public void setmonth(int month) {
this.month = month;
}
public void setYear(int year) {
this.year = year;
}
public int getDay() {
return day;
}
public int getMonth() {
return month;
}
public int getYear() {
return year;
}
finally i solved T_T very easy i take 2 weeks for solving
public Date1(int d, int m, int y) {
this.day = d;
this.month = m;
this.year = y;
}
public void addDay() {
month--;
Calendar m = Calendar.getInstance();
m.set(year, month, day);
m.add(day, 5);
java.sql.Date d = new java.sql.Date(m.getTimeInMillis());
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(" date is " + df.format(d));
}
Related
How can I set date in a DatePicker from a string (eg: 02/10/19):
Following is the code:
iqp_editDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(ActivityClass.this, (DatePickerDialog.OnDateSetListener) date1, y, m, d).show();
}
});
DatePickerDialog.OnDateSetListener date1 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
y = year;
m = month;
d = dayOfMonth;
dateMonth = month + 1;
dateYear = year;
}
};
Update: misunderstood the question:
Calendar cal = Calendar.getInstance()
cal.set(Calendar.HOUR_OF_DAY,18);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.DATE,2);
cal.set(Calendar.MONTH,9); //Month -1
//Or to set it from a String:
String string = "02/10/19";
DateFormat format = new SimpleDateFormat("dd/MM/yy", Locale.getDefault());
Date date = format.parse(string);
cal.setTimeInMillis(date.getTime());
new DatePickerDialog(getContext(),date1, cal
.get(Calendar.YEAR), cal .get(Calendar.MONTH),
cal .get(Calendar.DAY_OF_MONTH)).show();
A string is a character array. Meaning that you could just make a loop and set the different day, month and year values to different parts of the string.
String date = "02/19/19";
String year = "";
for(int i = 0; i < date.length; i++)
{
month += date.charAt(i);
...
}
Then you'd tell it when to switch from adding to month to day to year when it encounters '/'
if(date.charAt(i) == '/')
{
...
}
at the end of it all if you need to make it into an int then do
int month = Integer.parseInt("month");
sorry I've gotta be going somewhere so I couldn't just write the code out for ya but I'm sure you can figure it out from what I gave ya.
Following code works fine for me:
new DatePickerDialog(Activityclass.this, date1, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)).show();
DatePickerDialog.OnDateSetListener date1 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
view.setMinDate(1559327400);
y = year;
m = month;
d = dayOfMonth;
dateMonth = month + 1;
dateYear = year;
iqp_editDate.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
try {
epoch = new java.text.SimpleDateFormat("MM/dd/yyyy").parse(m + "/" + dayOfMonth + "/" + year).getTime() / 1000;
} catch (ParseException e) {
e.printStackTrace();
}
}
};
How does the compareTo() method for Dates work here in java? I know that when you compare two dates the result will always be 0 if equal, 1 if the date being
compared inside the compareTo() parameter is older, and -1 if the date inside the parameter is more recent.
//Just an example
String[] da = {"01/14/1975", "08/20/1975", "08/20/1975"};
SimpleDateFormat f = new SimpleDateFormat("MM/dd/yyyy");
Date d1 = new Date();
Date d2 = new Date();
//this outputs 1 because d2 is older than d1
d1 = f.parse(da[1]);
d2 = f.parse(da[0]);
System.out.println(d1.compareTo(d2));
//this outputs 0 because dates are the same
d1 = f.parse(da[1]);
d2 = f.parse(da[2]);
System.out.println(d1.compareTo(d2));
//this outputs -1 because d2 is more recent than d1
d1 = f.parse(da[0]);
d2 = f.parse(da[1]);
System.out.println(d1.compareTo(d2));
Now I want to compare dates without using compareTo() method or any built-in method in java. As much as possible I want to use just the basic operators in java.
What is the computation or the algorithm of the compareTo() method in comparing dates that enable it to return -1, 0, and 1?
Edit:
In the case at the sample problem at my book, using java.util.Date is forbidden, what is supposed to be done is to create your own date object like this:
public class DatesObj
{
protected int day, month, year;
public DatesObj (int mm, int dd, int yyyy) {
month = mm;
day = dd;
year = yyyy;
}
public int getMonth() { return month; }
public int getDay() { return day; }
public int getYear() { return year; }
}
Now how do I compare this as if like they're int and determine which is old and which is newer??
If you want to compare two dates just as if they were just plain-old integers, you must first turn each date into a plain-old integer. The easiest way to turn a year/month/day representation of a date into a plain-old integer, that can be effectively compared with plain-old integers from other dates, is to line the pieces up in exactly that order: year first, month next, day last:
// in DateObj class....
public int getDateInt() {
return (yyyy * 10000) + (mm * 100) + dd;
}
So for March 19, 2019, you get 20190319, and for December 7, 1941 you get 19411207; by comparing the "integerized" versions of the dates you can see that:
19411207 < 20190319, just as December 7, 1941 is earlier than March 19, 2019;
20190319 > 19411207, just as March 19, 2019 is later than December 7, 1941;
19411207 != 20190319, just as December 7, 1941 and March 19, 2019 are different dates
You're limited to dates within the Common Era and no more than about 200,000 years into the future with this particular implementation. But with a little tweaking, you could easily easily handle dates outside these ranges, an exercise that I will, as the textbooks so often say, leave as an exercise for the reader.
Implement Comparable and override compareTo().
class DatesObj implements Comparable<DatesObj>{
protected int day, month, year;
public DatesObj(int mm, int dd, int yyyy) {
month = mm;
day = dd;
year = yyyy;
}
public int getMonth() {
return month;
}
public int getDay() {
return day;
}
public int getYear() { return year; }
#Override
public int compareTo(DatesObj o) {
int diff = this.year - o.year;
if(diff != 0) {
return diff;
}
diff = this.month - o.month;
if(diff != 0) {
return diff;
}
return this.day - o.day;
}
}
Compare the years. If the years of both the dates are same, compare the months.
If the months are same, compare the dates.
public int compareDate(DatesObj d) {
if (this.year != d.year) {
if (this.year > d.year)
return 1;
else
return -1;
}
if (this.month != d.month) {
if (this.month > d.month)
return 1;
else
return -1;
}
if (this.day != d.day) {
if (this.day > d.day)
return 1;
else
return -1;
}
return 0;
}
Ref : https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html
Ref : https://developer.android.com/reference/java/util/Calendar
create own class with Interface Comparable
class DateCompare implements Comparable<Date>
{
protected int day, month, year;
public DateCompare(int mm, int dd, int yyyy) {
month = mm;
day = dd;
year = yyyy;
}
#Override
public int compareTo(Date o) {
Calendar cal = Calendar.getInstance();
cal.setTime(o);
int diff = this.year - cal.get(Calendar.YEAR);
if(diff != 0) {
return diff;
}
diff = this.month - cal.get(Calendar.MONTH);
if(diff != 0) {
return diff;
}
return this.day - cal.get(Calendar.DAY_OF_MONTH);
}
public int getMonth() {
return month;
}
public int getDay() {
return day;
}
public int getYear() { return year; }
}
And Other More Helpful
https://gist.github.com/Ashusolanki/fed3b6a680092985ac0ab93ed70fcd7c
private String postTime(Date date)
{
long postTime = date.getTime();
long atTime = System.currentTimeMillis();
long diff = atTime - postTime;
long sec = TimeUnit.SECONDS.convert(diff, TimeUnit.MILLISECONDS);
if (sec >= 60) {
long minit = TimeUnit.MINUTES.convert(diff, TimeUnit.MILLISECONDS);
if (minit >= 60) {
long hours = TimeUnit.HOURS.convert(diff, TimeUnit.MILLISECONDS);
if (hours >= 24) {
long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
return days + " Days Ago";
} else {
return hours + " Hours Ago";
}
} else {
return minit + " Minutes Ago";
}
} else {
return sec + " Secounds Ago";
}
}
I am building a Date class and when I try to create an object with it doesn't work. (errors in daysPerMonth)
However when I use setNewDay method outside of the object it does work.
Do you guys have any clues on what i'm doing wrong?
Here is my code:
public class Date{
private Dag day;
private Maand month;
private Jaar year;
private int maxday;
public Date(int day, int month, int year){
setDate(day, month, year);
}
public void setDate(int day, int month, int year){
this.month = new Maand(month);
setNewDay(day);
this.year = new Jaar(year);
}
private void daysPerMonth(){
int february;
if(year.getYear()%4 == 0) {
february = 29;
}else{
february = 28;
};
int[] daymonth={31,february,31,30,31,30,31,30,31,30,31,30};
maxday = daymonth[month.getMonth() -1];
}
public void setNewDay(int day){
daysPerMonth();
if(day > 0 && day <= maxday){
this.day = new Dag(day);
} else {
System.out.println("Wrong day");
}
}
}
I see a problem in the order of initialization :
public void setDate(int day, int month, int year){
this.month = new Maand(month);
setNewDay(day); // this method depends indirectly on this.year, which is not yet
// initialized (setNewDay calls daysPerMonth which calls
// year.getYear())
this.year = new Jaar(year);
}
Change it to :
public void setDate(int day, int month, int year){
this.year = new Jaar(year);
this.month = new Maand(month);
setNewDay(day);
}
Looking at the order of your calls, this
public void setDate(int day, int month, int year){
this.month = new Maand(month);
setNewDay(day);
this.year = new Jaar(year);
}
Should be
public void setDate(int day, int month, int year){
this.month = new Maand(month);
this.year = new Jaar(year);
setNewDay(day);
}
Because setNewDay() calls daysPerMonth() and that needs the year (Jaar).
Since you are calling the setNewDay() method before initialising the year ( which is by default null ). And setNewDay() method is instead calling the daysPerMonth() method which uses year but since year is currently null( which is by default value for every reference) You are getting NullPointerException
So you just need to initialise the year before calling the method setNewDay() :
public void setDate(int day, int month, int year){
this.month = new Maand(month);
this.year = new Jaar(year);
setNewDay(day); //call this method after setting up the year
}
So that when you call daysPerMonth() method your year contains valid data :
private void daysPerMonth(){
int february;
if(year.getYear()%4 == 0) { //now year is valid
february = 29;
}else{
february = 28;
}
int[] daymonth={31,february,31,30,31,30,31,30,31,30,31,30};
maxday = daymonth[month.getMonth() -1];
}
Depends on what year you try.
From memory you need three conditions to get February right: Isnot mod 100 & is mod 400
A method receives and integer representing a year and an integer representing a day of the week. The method should return a list of dates representing a given day of the week. For example, if the year is 2014 and the day of week is 2 then the method should return a list of dates representing all the Mondays in 2014.
public List<Date> getDatesforDayOfWeek(int year, int dayOfWeek) throws InvalidDateException
I'm not too sure what the best code would be. Any suggestions?
if (year <= 0) {
throw new InvalidDateException("Invalid year.");
}
if ((dayOfWeek < 1) || (dayOfWeek > 7)) {
throw new InvalidDateException("Invalid day.");
}
DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Check this implementation that would work for non-leap years (and for leap years with some modification)
public List<Date> getDatesforDayOfWeek(int year, int dayOfWeek)
throws InvalidDateException {
if (year <= 0) {
throw new InvalidDateException("Invalid year.");
}
if ((dayOfWeek < 1) || (dayOfWeek > 7)) {
throw new InvalidDateException("Invalid day.");
}
List<Date> dates = new ArrayList<Date>();
// Start with the given inputs
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, Calendar.JANUARY);
int day = cal.get(Calendar.DAY_OF_WEEK);
while (day != dayOfWeek) {
cal.add(Calendar.DATE, 1);
day = cal.get(Calendar.DAY_OF_WEEK);
}
// Make this 366 for a leap year
for (int i = 0; i < 365; i += 7) {
if (cal.get(Calendar.DAY_OF_WEEK) == dayOfWeek
&& cal.get(Calendar.YEAR) == year) {
dates.add(cal.getTime());
cal.add(Calendar.DATE, 7);
}
}
return dates;
}
public static void main(String[] args) throws InvalidDateException {
for (Date date : new DateList().getDatesforDayOfWeek(2014, 4)) {
System.out.println(date);
}
}
}
class InvalidDateException extends Exception {
public InvalidDateException(String string) {
super(string);
}
private static final long serialVersionUID = 1L;
}
If I understand your question, I would use a Calendar to solve this problem (actually I'd first pick Joda-Time, but otherwise Calendar because there are a lot of corner cases to handle) -
public static List<Date> getDatesforDayOfWeek(int year, int dayOfWeek) {
List<Date> al = new ArrayList<>();
if (dayOfWeek >= 1 && dayOfWeek <= 7) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH, 1);
while (cal.get(Calendar.DAY_OF_WEEK) != dayOfWeek) {
cal.add(Calendar.DAY_OF_MONTH, 1);
}
for (int i = 0; i < 52; i++) {
al.add(cal.getTime());
cal.add(Calendar.DAY_OF_MONTH, 7);
}
}
return al;
}
public static void main(String[] args) {
System.out.println(getDatesforDayOfWeek(2014, 2));
}
Output is (formatted, and 50 lines omitted, for display)
[Mon Jan 06 23:52:16 EST 2014,
...
Mon Dec 29 23:52:16 EST 2014]
Looking through all the answers they will provide you what you're looking for. Here is another approach I believe to be a little more efficient then the previous answers.
public static List<Date> GetDatesForDayOfWeek(int year, int dayOfWeek)
{
// Days in the week
final int DAYS_IN_WEEK = 7;
List<Date> dates = new ArrayList<Date>();
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, 0); // January
c.set(Calendar.DAY_OF_MONTH, 1); // The first
// Find the first day we are interested in
int offset = c.get(Calendar.DAY_OF_WEEK);
if(offset!= dayOfWeek)
{
c.add(Calendar.DATE, (dayOfWeek < offset ? (offset + 7) % 7 : (dayOfWeek - offset)));
}
while(c.get(Calendar.YEAR) == year)
{
dates.add(c.getTime());
c.add(Calendar.DATE, DAYS_IN_WEEK);
}
return dates;
}
public static void main(String[] args){
System.out.println("A list of all Sundays in 2014.");
List<Date> days = GetDatesForDayOfWeek(2014, Calendar.SUNDAY);
for(Date ad : days){
System.out.println(ad);
}
}
Running the above would give you every sunday in 2014 with the output of.
A list of all Sundays in 2014.
Sun Jan 05 23:49:56 EST 2014
...
Sun Dec 28 23:49:56 EST 2014
New Java8 DateTime API gives very clean methods to use for any Date, Time related code.
Below is my part on your query.
public class ExampleDayOfYear {
public static void main(String[] args) throws InvalidDateException {
List<LocalDate> list=getDatesforDayOfWeek(2020,2);
list.forEach(System.out::println);
System.out.println("Total dates: "+list.size());
}
public static String getDay(int day, int month, int year) {
LocalDate dt=LocalDate.of(year,month,day);
return dt.getDayOfWeek().toString();
}
private static int getDayOfYear(int year){
LocalDate dt = LocalDate.parse(year+"-01-01");
return dt.getDayOfWeek().getValue();
}
public static List<LocalDate> getDatesforDayOfWeek(int year, int dayOfWeek) throws
InvalidDateException{
List<LocalDate> list=new ArrayList<LocalDate>();
int differenceOfdaysToDayofWeek=0;
int firstDayOfYear= getDayOfYear(year); // Wednesday
int count=1;
// This method call gives the date of first Monday. Also, this method requires the differenceOfDate which we have found out from getDaysDifference.
LocalDate firstDateOfWeek=getFirstDateOfWeek(year,getDaysDifference(firstDayOfYear));
list.add(firstDateOfWeek);
while(firstDateOfWeek.getYear()== year){
firstDateOfWeek= getDateWeekWise(firstDateOfWeek);
if(firstDateOfWeek.getYear()==year){
count++;
list.add(firstDateOfWeek); }
}
return list;
}
// First Day is Wednesday, so we need ot get first date of the January, 2020.
private static int getDaysDifference(int firstDayOfYear){
int difDays=0;
int dayofWeekNum=Integer.valueOf(DayOfWeek.MONDAY.ordinal()+1);
// It gives the int value of DayOfWeek. e.g. if it's Monday it will give 0 because week ordinal value starts from 0.
if(firstDayOfYear==dayofWeekNum) {
}if(firstDayOfYear>dayofWeekNum){
difDays= dayofWeekNum+7 -firstDayOfYear;
}if(firstDayOfYear<dayofWeekNum)
{
difDays= dayofWeekNum -firstDayOfYear;
}
return difDays;
}
private static LocalDate getFirstDateOfWeek(int year,int differenceOfWeekDays){
LocalDate dt = LocalDate.of(year,01,01).plusDays(differenceOfWeekDays);
return dt;
}
private static LocalDate getDateWeekWise(LocalDate dt){
dt=dt.plusWeeks(1);
return dt;
}
}
class InvalidDateException extends Exception{
InvalidDateException(String s){
super(s);
}
}
What I'm trying to do is access an object, in this case date1 which has 3 attributes day, month and year. I'm attempting to make a method called showTomorrow() which will display the objects information 1 day infront in String format. This means I cannot alter the attributes of the original object.
I've written the Data.java program and it's shown below, if someone could point me in the right direction or show me what it would be really helpfull.
This is what I'd essentially be running on my main method I believe.
**Date date1 = new Date(30, 12, 2013)** // instantiate a new object with those paramaters
**date1.showDate();** // display the original date
**date1.tomorrow();** // shows what that date would be 1 day infront
The problem is right now it's not displaying anything. I thought that by saying dayTomorrow = this.day++; I was adding it's default value + 1 day to the variable dayTomorrow.
public class Date
{
private int day;
private int month;
private int year;
private int dayTomorrow;
private int monthTomorrow;
private int yearTomorrow;
public Date()
{
day = 1;
month = 1;
year = 1970;
}
public Date(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
}
public void setDate(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
}
public String getDate()
{
String strDate;
strDate = day + "/" + month + "/" + year;
return strDate;
}
public String getTomorrow()
{
String strTomorrow;
strTomorrow = dayTomorrow + "/" + monthTomorrow + "/" + yearTomorrow;
return strTomorrow;
}
public String tomorrow()
{
dayTomorrow = this.day++;
monthTomorrow = this.month;
yearTomorrow = this.year;
if(dayTomorrow > 30)
{
dayTomorrow = 1;
monthTomorrow = this.month++;
}
if(monthTomorrow > 12)
{
monthTomorrow = 1;
yearTomorrow = this.year++;
}
return getTomorrow();
}
public void showDate()
{
System.out.print("\n\n THIS OBJECT IS STORING ");
System.out.print(getDate());
System.out.print("\n\n");
}
public void showTomorrow()
{
System.out.print("\n\n THE DATE TOMORROW IS ");
System.out.print(getTomorrow());
System.out.print("\n\n");
}
public boolean equals(Date inDate)
{
if(this.day == inDate.day && this.month == inDate.month && this.year == inDate.year)
{
return true;
}
else
{
return false;
}
}
}
You just need to use ++this.day, ++this.month and ++this.year. When you use this.day++ it returns the previous date value, not the new. Putting the ++ in the front solves the problem. Also, it changes the day value... you might want to change that to this.day + 1.
Are You calling showDate() after date1.tomorrow() to show your output?
or instead of date1.tomorrow(); call date1.showTomorrow();
Have a look at this : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
post incremention ...
You could use the native date support in java but I figured you are just practicing right?
This should do the trick:
public class Date {
private int day = 1;
private int month = 1;
private int year = 1970;
private int dayTomorrow = day+1;
private int monthTomorrow;
private int yearTomorrow;
public Date()
{
tomorrow();
}
public Date(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
tomorrow();
}
public void setDate(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
}
public String getDate()
{
String strDate;
strDate = day + "/" + month + "/" + year;
return strDate;
}
public String getTomorrow()
{
String strTomorrow;
strTomorrow = dayTomorrow + "/" + monthTomorrow + "/" + yearTomorrow;
return strTomorrow;
}
public void tomorrow()
{
monthTomorrow = this.month;
yearTomorrow = this.year;
if(dayTomorrow > 30)
{
dayTomorrow = 1;
monthTomorrow = this.month++;
}
if(monthTomorrow > 12)
{
monthTomorrow = 1;
yearTomorrow = this.year++;
}
}
public void showDate()
{
System.out.print("\n\n THIS OBJECT IS STORING ");
System.out.print(getDate());
System.out.print("\n\n");
}
public void showTomorrow()
{
System.out.print("\n\n THE DATE TOMORROW IS ");
System.out.print(getTomorrow());
System.out.print("\n\n");
}
public boolean equals(Date inDate)
{
if(this.day == inDate.day && this.month == inDate.month && this.year == inDate.year)
{
return true;
}
else
{
return false;
}
}
}
Look carefully for any changes i've made ;)
Here's the main:
public static void main(String[] args) {
Date d = new Date();
d.showDate();
d.showTomorrow();
}