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
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
This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
How to subtract X day from a Date object in Java?
(10 answers)
Closed 8 years ago.
Can any one help me with the code for adding some number of days to any date..?
For example today is 11-04-2014. I want 15-04-2014 + 3 days output:18-04-2014.
My question is not adding dates to current date..
With Java 8, you can write:
import java.time.LocalDate;
LocalDate date = LocalDate.of(2014, 4, 11);
LocalDate newDate = date.plusDays(3);
System.out.println(newDate); // Prints 2014-04-14
Its that simple.
String dateString = "11-04-2014" // Say you have a date in String format
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy"); // Create an instance of SimpleDateFormat with the right format.
Date date = format.parse(dateString); // Then parse the string, this will need a try catch statement.
Calendar calendar = Calendar.getInstance(); // Get an instance of the calendar.
calendar.setTime(date); // Set the time of the calendar to the parsed date
calendar.add(Calendar.DATE, 3); // Add the days to the calendar
String outputFormat = format.format(calendar.getTime());
import java.util.Calendar;
import java.text.SimpleDateFormat;
public class A {
public static void main(String[] args) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.MONTH, 1);
calendar.set(Calendar.YEAR, 2012);
calendar.add(Calendar.DAY_OF_MONTH, 3);
System.out.println(simpleDateFormat.format(calendar.getTime()));
}
}
You can use the calendar function:
Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, NO_OF_DAYS_TO_ADD);
Date addedDays = cal.getTime();
DateInstance is the date you are using. addedDays can be formatted using SimpleDateFormat to display in any date format that you would like to use.
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);
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
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.
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();
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).
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
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];
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
Date date = new Date();
System.out.println(date.toString());
}
}