sgrgmngt
sgrgmngt

Reputation: 917

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.

Upvotes: 0

Views: 8489

Answers (5)

abey
abey

Reputation: 1

import java.util.Date;

public class DateDemo {
    public static void main(String args[]) {
        Date date = new Date();
        System.out.println(date.toString());
    }
}

Upvotes: 0

user425367
user425367

Reputation:

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();

Upvotes: 3

paxdiablo
paxdiablo

Reputation: 881663

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).

Upvotes: 2

Rasel
Rasel

Reputation: 15477

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];

Upvotes: 0

Kris
Kris

Reputation: 5792

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

Upvotes: 1

Related Questions