All this is my program where i am trying the folowing
Below is my code for Dates functionality...
import java.text.SimpleDateFormat;
import java.util.*;
import java.text.*;
public class DateToCalender {
public static void main(String args[]){
//String strFormat="yyyymmdd";
//DateFormat myDateFormat = new SimpleDateFormat(strFormat);
DateFormat df= new SimpleDateFormat("yyyyMMdd");
df.setLenient(false);
Calendar start=Calendar.getInstance();
try {
Date fromDt =(Date)df.parse("20111207");
//Date myDate = new Date();
//myDate = (Date)myDateFormat.parse("20111207");
//myGDate.setTime(myDate);
start.setTime(fromDt);
start.set(Calendar.MONTH,(start.get(Calendar.MONTH)+1));
System.out.println(start);
System.out.println(start.get(Calendar.YEAR));
System.out.println(start.get(Calendar.MONTH)-1);
System.out.println(start.get(Calendar.DAY_OF_MONTH));
//System.out.println("From My class"+myGDate.get(Calendar.MONTH));
//System.out.println("From My class new month"+(myGDate.get(Calendar.MONTH)+1));
} catch (ParseException e) {
System.out.println("Invalid Date Parser Exception ");
e.printStackTrace();
}
}
}
when iam executing this code iam getting folowwing o/p
java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA
=1,YEAR=2011,MONTH=12,WEEK_OF_YEAR=50,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=341,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=19800000,DST_OFFSET=0]
2011
0
7
**
issue is :
Though iam entering date as 2011/12/07
I am getting year as 2011
month as 0
date as 7
Can some one help in resolving above issue
Could any body please let me know , how this can be resolved .
Don't subtract 1 from the month; Calendar already knows that it's zero-based.
It seems to me like you're doing far too much work here. Why can't you just do this?
private static final DateFormat DEFAULT_DATE_FORMAT;
static {
DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
DEFAULT_DATE_FORMAT.setLenient(false);
}
public Calendar getCalendar(String dateAsString) {
Calendar value = Calendar.getInstance();
Date d = DEFAULT_DATE_FORMAT.parse(dateAsString);
value.setTime(d);
return value;
}
There's an exception that needs to be added to the method signature, but you get the idea. Look at the Calendar javadocs. This could be easier.
setting a condition to check the month can resolve your problem:
try {
Date fromDt =(Date)df.parse("20131209");
start.setTime(fromDt);
start.set(Calendar.MONTH,(start.get(Calendar.MONTH)));
int month = start.get((Calendar.MONTH));
if (month ==11){
System.out.println(start.get(Calendar.YEAR));
System.out.println(start.get(Calendar.MONTH)+1);
System.out.println(start.get(Calendar.DAY_OF_MONTH));
}else{
start.set(Calendar.MONTH,(start.get(Calendar.MONTH))+1);
System.out.println(start.get(Calendar.YEAR));
System.out.println(start.get(Calendar.MONTH));
System.out.println(start.get(Calendar.DAY_OF_MONTH));
}
}
this will print out :
2013
12
9
Related
This question already has answers here:
SimpleDateFormat ignoring month when parsing
(4 answers)
How to add one day to a date? [duplicate]
(18 answers)
When Using Date Picker In Android It is Picking the Wrong Date [duplicate]
(1 answer)
Closed 3 years ago.
I'm trying to add days that exceed the month days. example July 1,2019 and I add 32 days so the result would be August 2,2019.
SimpleDateFormat format = new SimpleDateFormat("mm/dd/yyy");
SimpleDateFormat Dateformat = new SimpleDateFormat("mm/dd/yyy");
String getDate = date_pick.getText().toString();
Date mDate;
Date result_desu;
try {
mDate = format.parse(getDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(mDate);
calendar.add(Calendar.DATE, 32);
String formattedDate = Dateformat.format(calendar.getTime());
date_result.setText(formattedDate); // format output
} catch (ParseException e) {
e.printStackTrace();
}
I've been using this code but it turns out the days only reset with the same month example: July 1,2019 ; result: July 2,2019.
Try this:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.text.ParseException;
class Main{
public static void main(String args[]){
String oldDate = "2019-07-1";
System.out.println("Date before Addition: "+oldDate);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
try{
c.setTime(sdf.parse(oldDate));
}catch(ParseException e){
e.printStackTrace();
}
c.add(Calendar.DAY_OF_MONTH, 32);
String newDate = sdf.format(c.getTime());
System.out.println("Date after Addition: "+newDate);
}
}
Output:
Date before Addition: 2019-07-1
Date after Addition: 2019-08-02
I was trying to block incompatible date in input. So I intentionally gave wrong date as string. I set calendar.setLenient to false hoping that it would not allow date to parse. But It pass through it. Below is my code:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Test {
public static void main(String[] args) throws Exception{
try {
String from ="2018-15-18";
String to = "2018-15-18";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calender1 = Calendar.getInstance();
Calendar calender2 = Calendar.getInstance();
calender1.setLenient(false);
calender2.setLenient(false);
calender1.setTime(sdf.parse(from));
calender2.setTime(sdf.parse(to));
Date dtFrom = calender1.getTime();
Date dtTo = calender2.getTime();
System.out.println(sdf.format(dtFrom));
if((from!=null && !from.isEmpty())&&(to!=null && !to.isEmpty())&&(dtFrom!=null && dtTo!=null))
System.out.println("ok");
else
System.out.println("not ok");
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
As I have given wrong date i.e. month 15 does not exist. So I was expecting exception on line calender1.setTime(sdf.parse(from)); but it pass through and printing date value as : 2019-03-18. I did not wanted that. Why is it so? How can I make sure wrong date input should not be entertained further in my code once it is not able to parse.
I have the following code in Java
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Test {
public static void main(String[] args) {
try {
SimpleDateFormat SDF = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ss");
Calendar date = Calendar.getInstance();
date.setTime(SDF.parse("2011-02-01T00:00:00"));
System.out.println(SDF.format(date.getTime()));
} catch (Exception e) {
}
}
}
I expect to see in the console the following string
2011-02-01T00:00:00
instead I see
2011-12-26T00:00:00
What can be wrong?
I change the format: "yyyy-MM-dd'T'HH:mm:ss"
SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Calendar date = Calendar.getInstance();
date.setTime(SDF.parse("2011-02-01T00:00:00"));
System.out.println(SDF.format(date.getTime()));
The output is 2011-02-01T00:00:00
"Y": week year
"y": year
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
From the documentation:
"If week year 'Y' is specified and the calendar doesn't support any week years, the calendar year ('y') is used instead. The support of week years can be tested with a call to getCalendar().isWeekDateSupported()."
In some calendar "Y" and "y" are the same, but is not the case of the gregorian calendar.
https://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#isWeekDateSupported%28%29
I am using the following code to check the birthday of a person:
public class Test_Year {
static int yearsInterval =1;
static int yearsSpecial =0;
static Date dateYearsReg;
public static void main(String[] args){
yearsToNotify(2013, "0001-10-02");
}
public static void yearsToNotify(int yearsElapsedSinceBirth, String dateOfBirth){
Date dt = Convert(d);
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
System.out.println();
yearsSpecial = yearsInterval*(1+(years/yearsInterval));
System.out.println(yearsSpecial);
cal.add(Calendar.YEAR, yearsSpecial);
dateYearsReg = cal.getTime();
System.out.println(dateYearsReg);
}
public static Date Convert(String S){
String dateStr = S;
Date d1 = null ;
try {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
d1 = f.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return d1;
}
}
Ideally the above should give me the next birthday and the year should be 2014, however I get the year as 2015. The system date being todays date that is first of October 2014. Any hints?
In the baove if I give a call like: yearsToNotify(41, "1972-10-17"); I get the correct values. Seems this is a problem with results when I use the year as 0001.
I believe the problem stems from this line
cal.add(Calendar.YEAR, yearsSpecial);
If we look at the javadoc for ADD we see it is this
public abstract void add(int field,
int amount)
Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:
Instead you want to be using set:
cal.set(Calendar.YEAR, yearsSpecial);
I am using this code to get previous date but i would like to get the date excluding Saturday and Sunday
the code that i use to get previous date :
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static String previousDateString(String dateString)
throws ParseException {
// Create a date formatter using your format string
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// Parse the given date string into a Date object.
// Note: This can throw a ParseException.
Date myDate = dateFormat.parse(dateString);
// Use the Calendar class to subtract one day
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -1);
// Use the date formatter to produce a formatted date string
Date previousDate = calendar.getTime();
String result = dateFormat.format(previousDate);
return result;
}
public static void main(String[] args) {
String dateString = "2012-08-20";
try {
// This will print 2012-08-19
System.out.println(previousDateString(dateString));
} catch (ParseException e) {
System.out.println("Invalid date string");
e.printStackTrace();
}
}
}`
It works fine but need to get the previous date which is not Saturday or Sunday.
Regards
You should have to get DAY_OF_WEEK from the calendar object and if its next day is MONDAY then subtract three days or if SUNDAY then subtract two days from the date/calendar object.
calendar.setTime(myDate);
int dayOfWeek=calendar.get(Calendar.DAY_OF_WEEK);
if(dayOfWeek==Calendar.MONDAY)
calendar.add(Calendar.DAY_OF_YEAR, -3);
else
if(dayOfWeek==Calendar.SUNDAY)
calendar.add(Calendar.DAY_OF_YEAR, -2);
else
calendar.add(Calendar.DAY_OF_YEAR, -1);