Add or subtract
years to current date
import java.util.Calendar;
public class AddYearToCurrentDate
{
public static void main(String[] args)
{
Calendar now = Calendar.getInstance();
System.out.println("Current date : " +
(now.get(Calendar.Month) + 1)
+ "-"
+ now.get(Calendar.Date)
+ "-"
+ now.get(Calendar.Year));
now.add(Calendar.Year,1);
System.out.println("date after one year:"+(now.get(Calendar.Month)
+ 1)
+ "-"
+ now.get(Calendar.Date)
+ "-"
+ now.get(Calendar.Year));
now =Calendar.getInstance();
now.add(Calendar.Year,-100);
System.out.println("date before 100
years:"+(now.get(Calendar.Month) + 1)
+ "-"
+ now.get(Calendar.Date)
+ "-"
+ now.get(Calendar.Year));
}
}
Compare date time using after method
import java.util.Calendar;
public class CompareDateTimesUsingAfter
{
public static void main(String[] args)
{
Calendar futureCal = Calendar.getInstance();
futureCal.set(Calendar.Year, 2010);
Calendar now = Calendar.getInstance();
System.out.println("Current date : " +
(now.get(Calendar.Month) + 1)
+ "-"
+ now.get(Calendar.Date)
+ "-"
+ now.get(Calendar.Year));
System.out.println("Is futureCal after now ? : "
+ futureCal.after(now));
}
}
Compare date
time using before method
import java.util.Calendar;
public class CompareDateTimesUsingBefore
{
public static void main(String[] args)
{
Calendar old = Calendar.getInstance(); old.set(Calendar.Year,
1990);Calendar now = Calendar.getInstance();
System.out.println("Is old before now ? : " +
old.before(now));
}
}
Display Day of
Week
import java.util.Calendar;
public class DisplayDayOfWeek
{
public static void main(String[] args)
{
Calendar now = Calendar.getInstance();
System.out.println("Current date : " +
(now.get(Calendar.Month) + 1)
+ "-"
+ now.get(Calendar.Date)
+ "-"
+ now.get(Calendar.Year));
String[] strDays = new String[]
{
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thusday",
"Friday",
"Saturday"
};
System.out.println("Current day is : " +
strDays[now.get(Calendar.Day_Of_Week) - 1]
);
}
}
Display Month
of year
import java.util.Calendar;
public class DisplayMonthOfYear
{
public static void main(String[] args)
{
Calendar now = Calendar.getInstance();
System.out.println("Current date : " +
(now.get(Calendar.Month) + 1)
+ "-"
+ now.get(Calendar.Date)
+ "-"
+ now.get(Calendar.Year));
String[] strMonths = new String[]
{
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
};
System.out.println("Current month is : " +
strMonths[now.get(Calendar.Month)]
);
}
}
No comments:
Post a Comment