I am taking in two dates as command line arguments and want to check if the first one is after the second date. the format of the date it "dd/MM/yyy".
Example: java dateCheck 01/01/2014 15/03/2014
also i will need to check if a third date hardcoded into the program is before the second date.
try {
System.out.println("Enter first date : (dd/MM/yyyy)");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = sdf.parse(bufferRead.readLine());
System.out.println("Enter second date : (dd/MM/yyyy)");
Date date2 = sdf.parse(bufferRead.readLine());
System.out.println(date1 + "\n" + date2);
if (date1.after(date2)) {
System.out.println("Date1 is after Date2");
} else {
System.out.println("Date2 is after Date1");
}
} catch (IOException e) {
e.printStackTrace();
}
To compare two dates :
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyy");
Date firstDate = sdf.parse("01/01/2014");
Date secondDate = sdf.parse("15/03/2014");
if(firstDate.before(secondDate)){
System.out.println("firstDate < secondDate");
}
else if(firstDate.after(secondDate)){
System.out.println("firstDate > secondDate");
}
else if(firstDate.equals(secondDate)){
System.out.println("firstDate = secondDate");
}
tl;dr
LocalDate ld1 = LocalDate.parse( "01/01/2014" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ;
LocalDate ld2 = LocalDate.parse( "15/03/2014" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ;
LocalDate ld3 = LocalDate.of( 2014 , Month.JULY , 1 ) ;
Boolean isFirstDateBeforeSecondDate = ld1.isBefore( ld2 ) ;
Boolean isThirdDateBeforeSecondDate = ld3.isBefore( ld2 ) ;
Boolean result = ( isFirstDateBeforeSecondDate && isThirdDateBeforeSecondDate ) ;
return result ;
Using java.time
The modern approach uses the java.time classes rather than the troublesome old legacy date-time classes (Date, Calendar, etc.).
The LocalDate class represents a date-only value without time-of-day and without time zone.
Define a formatting pattern to match your input strings using the DateTimeFormatter class.
String input = "15/03/2014" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( input , f );
ld.toString(): 2014-03-15
To specify a fixed date, pass year, month, and dayOfMonth. For the month, you may specify a number, sanely numbered 1-12 for January-December (unlike the crazy 0-11 in the legacy classes!). Or you may choose to use the Month enum objects.
LocalDate firstOf2014 = LocalDate.of( 2014 , Month.JANUARY , 1 );
Compare using isBefore, isEqual, or isAfter methods.
Boolean isInputDateBeforeFixedDate = ld.isBefore( firstOf2014 ) ;
isInputDateBeforeFixedDate.toString(): false
ISO 8601
If possible, replace your particular date string format with the standard ISO 8601 format. That standard defines many useful practical unambiguous string formats for date-time values.
The java.time classes use the standard formats by default when parsing/generating strings. You can see examples in the code above. For a date-only value, the standard format is YYYY-MM-DD.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Use SimpleDateFormat to convert a string to Date.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = sdf.parse("01/01/2017");
Date has before and after methods and can be compared to each other as follows:
if(todayDate.after(historyDate) && todayDate.before(futureDate)) {
// In between
}
For an inclusive comparison:
if(!historyDate.after(todayDate) && !futureDate.before(todayDate)) {
/* historyDate <= todayDate <= futureDate */
}
To read a date and check before:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyy");
try {
Date date1 = sdf.parse(string1);
Date date2 = sdf.parse(string2);
if(date1.before(date2)) {
// do something
}
} catch(ParseException e) {
// the format of the read dates is not the expected one
}
Related
I'm struggling to find the error in my code here. paytotal is coming out 0 when it should have a number.
firstDayOfPaycheck is the date Oct. 23rd 2020.
lastDayOfPaycheck is the date Nov. 6 2020.
My Simple date format sdf is "MMM dd, yyyy".
string dateInQuestion passed into runPayroll is "Oct. 31, 2020" which came originally from the same sdf as above.
I'm new to java and haven't dealt with manipulating the calendar like this. It feels like the code below should work.
private void runPayroll(String dateInQuestion, long payForTask){
c.setTime(firstDayOfPaycheck);
//loop through days of paycheck. number from time.compareTo(time2) is negative while time is before time2
while(c.getTime().compareTo(lastDayOfPaycheck)<=0){
if(dateInQuestion != null) {
Date questionDate = sdf.parse(dateInQuestion, new ParsePosition(0));
if (c.getTime().compareTo(questionDate) == 0) {
payTotal += payForTask;
}
}
c.add(Calendar.DAY_OF_YEAR, 1);
}
} //ran inside the query to get the total pay
private void buildPayrollDash(){
String strPayrollAmt = "$" + payTotal;
String startDate = sdf.format(firstDayOfPaycheck);
String trimmedStart = startDate.split(",")[0]; //cuts out the year in the date
String endDate = sdf.format(lastDayOfPaycheck);
String trimmedEnd = endDate.split(",")[0];
int holdBack = sharedPreferences.getInt("payroll holdback", 7);
c.setTime(lastDayOfPaycheck);
c.add(Calendar.DAY_OF_YEAR, holdBack);
String payDate = sdf.format(c.getTime());
String trimmedPaydate = payDate.split(",")[0];
tvPayrollTimefame.setText("Pay from " + trimmedStart + " - " + trimmedEnd);
tvPayrollAmount.setText(strPayrollAmt + " due " + trimmedPaydate);
I'm struggling to find the error in my code here.
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes. Never use Date, Calendar, GregorianCalendar, or their relatives.
firstDayOfPaycheck is the date Oct. 23rd 2020.
Use LocalDate to represent a date without time-of-day and without time zone.
LocalDate firstDayOfPayPeriod = LocalDate.of( 2020 , Month.OCTOBER , 23 ) ;
lastDayOfPaycheck is the date Nov. 6 2020.
You'll find date-time handling much easier if you define your spans-of-time using the Half-Open approach. The beginning is inclusive while the ending is exclusive. So instead of focusing on the last day of the pay period, focus on the first day of the following period.
LocalDate firstDayOfSuccessivePayPeriod = LocalDate.of( 2020 , 11 , 7 ) ;
Tip: You can represent the date range of the pay period as a LocalDateRange object if you add the ThreeTen-Extra library to your Java project.
My Simple date format sdf is "MMM dd, yyyy".
You should not be mixing business logic with localization code. Custom formatting of date-times should only be done for presentation to the user.
When exchanging date-time values textually as data, use the standard ISO 8601 formats. For a date-only value, the standard format is YYYY-MM-DD. The java.time use ISO 8601 formats by default, so no need to specify any formatting pattern.
string dateInQuestion passed into runPayroll is "Oct. 31, 2020" which came originally from the same sdf as above.
LocalDate dateInQuestion = LocalDate.parse( "2020-10-31" ) ;
If you must accommodate an input of formatted date string rather than standard ISO 8601 format, use DateTimeFormatter. This has been covered many many times already on Stack Overflow, so search for more info.
And rather than check for valid data later, check your inputs early in your code. “Fail fast” is the saying.
try
{
LocalDate dateInQuestion = LocalDate.parse( "2020-10-31" );
}
catch ( DateTimeParseException e )
{
// … Handle faulty input.
e.printStackTrace();
}
I'm new to java and haven't dealt with manipulating the calendar like this. It feels like the code below should work.
Your code will be much simpler when using java.time. For one thing, the java.time classes offer convenient isBefore, isAfter, and isEqual methods, so no need for clumsy compareTo calls.
LocalDate firstDayOfPayPeriod = LocalDate.of( 2020 , Month.OCTOBER , 23 );
LocalDate firstDayOfSuccessivePayPeriod = LocalDate.of( 2020 , 11 , 7 );
String input = "2020-10-31";
LocalDate dateInQuestion = null;
try
{
dateInQuestion = LocalDate.parse( input );
}
catch ( DateTimeParseException e )
{
// Handle faulty input.
e.printStackTrace();
}
// Validate dates.
Objects.requireNonNull( firstDayOfPayPeriod );
Objects.requireNonNull( firstDayOfSuccessivePayPeriod );
Objects.requireNonNull( dateInQuestion );
if ( ! firstDayOfPayPeriod.isBefore( firstDayOfSuccessivePayPeriod ) )
{
throw new IllegalStateException( "…" );
}
if ( dateInQuestion.isBefore( firstDayOfPayPeriod ) )
{
throw new IllegalStateException( "…" );
}
if ( ! dateInQuestion.isBefore( firstDayOfSuccessivePayPeriod ) )
{
throw new IllegalStateException( "…" );
}
long payPerDay = 100;
long partialPay = 0;
LocalDate localDate = firstDayOfPayPeriod;
while ( localDate.isBefore( firstDayOfSuccessivePayPeriod ) )
{
if ( localDate.isBefore( dateInQuestion ) )
{
partialPay = ( partialPay + payPerDay );
}
// Set up the next loop.
// Notice that java.time uses immutable objects. So we generate a new object based on another’s values rather than alter (mutate) the original.
localDate = localDate.plusDays( 1 ); // Increment to next date.
}
System.out.println( "Partial pay earned from firstDayOfPayPeriod " + firstDayOfPayPeriod + " to dateInQuestion " + dateInQuestion + " is " + partialPay );
See this code run live on IdeOne.com.
Partial pay earned from firstDayOfPayPeriod 2020-10-23 to dateInQuestion 2020-10-31 is 800
With more experience in programming Java, you may want to do this kind of work using streams. See LocalDate::datesUntil.
By the way, if you want to skip weekends, add something like this:
Set< DayOfWeek > weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY ) ;
…
if ( weekend.contains( localDate.getDayOfWeek() ) ) { … }
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
I want to compare two dates to categories Browser History...
I have seen too many posts but didn't get any helpful,
My code is as :
private static String calculateDate()
{
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, -10);
return simpleDateFormat.format(new Date(calendar.getTimeInMillis()));
}
private static String today()
{
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR,0);
return simpleDateFormat.format(new Date(calendar.getTimeInMillis()));
}
public void getBHistory()
{
long startdates = 0;
long enddates = 0;
Date endDate = null;
Date startDate=null;
try
{
startDate = (Date)new SimpleDateFormat("yyyy-MM-dd")
.parse(calculateDate());
endDate = (Date)new SimpleDateFormat("yyyy-MM-dd")
.parse(today());
startdates = startDate.getTime();
enddates = endDate.getTime();
} catch (ParseException e)
{
e.printStackTrace();
}
// 0 = history, 1 = bookmark
String sel = Browser.BookmarkColumns.BOOKMARK + " = 0" + " AND "
+ Browser.BookmarkColumns.DATE + " BETWEEN ? AND ?";
Cursor mCur = m_oContext.getContentResolver().query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, sel,
new String[]{
"" + startdates, "" + enddates
}, null);
mCur.moveToFirst();
String title = "";
String date_time = "";
if (mCur.moveToFirst() && mCur.getCount() > 0)
{
while (!mCur.isAfterLast())
{
title = mCur.getString(mCur
.getColumnIndex(Browser.BookmarkColumns.TITLE));
date_time = mCur.getString(mCur
.getColumnIndex(Browser.BookmarkColumns.DATE));
SimpleDateFormat simpleDate= new SimpleDateFormat("yyyy-MM-dd");
String curDate=simpleDate.format(new Date(Long.parseLong(date_time)));
Toast.makeText(m_oContext,"History Time : "+curDate,Toast.LENGTH_SHORT).show();
Toast.makeText(m_oContext,"Limit Time : "+calculateDate(),Toast.LENGTH_SHORT).show();
//TODO: Compare these two dates here
mCur.moveToNext();
}
}
}
I want to do if the History date is earlier than ten days ago then notify the user.
Any kind of help will be appreciated ,thank you.
tl;dr
Boolean alertUser =
LocalDate.parse( "2016-01-02" )
.isBefore(
LocalDate.now( ZoneId.of( “America/Montreal” ) )
.minusDays( 10 )
) ;
java.time
You are using troublesome old date-time classes now supplanted by the java.time classes.
Time zone
Your code ignores the crucial issue of time zone in determining a date such as “today”.
Example code
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( “America/Montreal” );
LocalDate today = LocalDate.now( z );
Your input strings are in standard ISO 8601 format. The java.time classes use ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate target = LocalDate.parse( "2016-01-02" );
You say the boundary is ten days ago. Use the plus or minus methods to determine future/past dates.
LocalDate tenDaysAgo = today.minusDays( 10 );
Compare using compareTo, equals, isBefore, and isAfter methods.
Boolean alertUser = target.isBefore( tenDaysAgo );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Calendar is comparable so you can just use compare to. I would make curDate a calendar. Then (curDate.compareTo(calculatedDate) < 0) will be true if curDate is earlier than calculatedDate which you've set to ten days before today.
You can use
before()
Or
after()
to compare your calculated date with today's date
public boolean isHDateEarlier(String historyDate){
String[] historySplitStrings= historyDate.split("-");
String[] tenDaysEarlierStrings = calculateDate().split("-");
int historyYear = Integer.parseInt(historySplitStrings[0]);
int daysYear = Integer.parseInt(tenDaysEarlierStrings [0]);
int historyMonth = Integer.parseInt(historySplitStrings[1]);
int daysMonth = Integer.parseInt(tenDaysEarlierStrings [1]);
int historyDay = Integer.parseInt(historySplitStrings[2]);
int daysDay = Integer.parseInt(tenDaysEarlierStrings [2]);
if(historyYear < daysYear ){//check year
return true;
}
if(historyMonth < daysMonth &&
historyYear <= daysYear ){//check month
return true;
}
if(historyDay < daysDay &&
historyYear <= daysYear &&
historyMonth <= daysMonth){//check day
return true;
}
return false;
}
Just call :
isHDateEarlier(curDate);
I had a problem with comparing dates a week ago, and searched for answers and this helped me: Find nearest date from a list. - The last answer talks about NavigableSet<>
Try using NavigableSet<Date> such as TreeSet<> and put your dates in the list.
Than compare with lower or higher
I'm using a method that calculates the next Monday from a given date string.
public static String getStartOfNextWeek(String DATE){
String format = "dd.MM.yyyy";SimpleDateFormat df = new SimpleDateFormat(format);
Date date = null;
try {
date = df.parse(DATE);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
int year = cal.get(Calendar.YEAR);
Calendar calendar = new GregorianCalendar();
calendar.clear();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.WEEK_OF_YEAR, week);
//add 8 days to get next weeks Monday
calendar.add(Calendar.DAY_OF_WEEK, 8);
Date startDate = calendar.getTime();
SimpleDateFormat df2 = new SimpleDateFormat("dd.MM.yyyy");
String start = df2.format(startDate);
return start;
This work perfectly fine over a single calendar year, but when I'm passing a value that spans two calendar years problems arise.
For example:
input: 15.12.2014
output: 22.12.2014 CORRECT
input: 22.12.2014
output: 29.12.2014 CORRECT
input: 29.12.2014
output: 6.1.2014 INCORRECT
I realize where the mistake is located, since it takes WEEK_OF_YEAR as "1", but YEAR as "2014", so the output is technically correct. Just wrong for my purpose.
How would i best tell the calendar object that i want the next monday in week 1, but 2015?
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This Answer is left intact as history. See my newer Answer.
Joda-Time
The Joda-Time library, version 2.5, gets the correct answer. And gets it more easily.
// Parse input string.
String input = "29.12.2014";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd.MM.yyyy" );
LocalDate inputLocalDate = formatter.parseLocalDate( input );
// Find desired Monday.
LocalDate possibleMonday = inputLocalDate.withDayOfWeek( DateTimeConstants.MONDAY );
// The possible Monday could be past, present, or future of our input date. Adjust as needed.
LocalDate desiredMonday = null;
if ( possibleMonday.isBefore( inputLocalDate ) || possibleMonday.isEqual( inputLocalDate ) ) {
desiredMonday = possibleMonday.plusWeeks( 1 ); // If the possible Monday is past or present, add a week to get *next* Monday.
} else {
desiredMonday = possibleMonday; // If the possible Monday is future, use it.
}
String output = formatter.print( desiredMonday );
Dump to console.
System.out.println( "input : " + input );
System.out.println( "inputLocalDate : " + inputLocalDate );
System.out.println( "desiredMonday : " + desiredMonday );
System.out.println( "output : " + output );
When run.
input : 29.12.2014
inputLocalDate : 2014-12-29
desiredMonday : 2015-01-05
output : 05.01.2015
There's something weird when combining Date and Calender, when it comes to parsing dates, using only Calender it works great;
String[] dt = dateStr.split("\\.");
GregorianCalendar cal = new GregorianCalendar(Integer.parseInt(dt[2]), (Integer.parseInt(dt[1])-1), Integer.parseInt(dt[0]));
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.clear(Calendar.DAY_OF_WEEK);
cal.add(Calendar.DATE, 7);
System.out.println(cal.get(Calendar.YEAR) + "." + (cal.get(Calendar.MONTH)+1) + "." + cal.get(Calendar.DATE));
Edit: You have to subtract 1 from the month, since calendar expects the months to range from 0 to 11.
(Calendar.JANUARY == 0) //true
tl;dr
LocalDate.parse(
"29.12.2014" ,
DateTimeFormatter.ofPattern( "dd.MM.uuuu" )
).with(
TemporalAdjusters.next( DayOfWeek.MONDAY )
)
2015-01-05
java.time
The modern approach uses the java.time classes.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM.uuuu" )
LocalDate ld = LocalDate.parse( "29.12.2014" , f ) ;
To move to another date, use a TemporalAdjuster implementation found in the TemporalAdjusters class. Specify the desired day-of-week with DayOfWeek enum object. No problem crossing end-of-year/start-of-year.
LocalDate followingMonday = ld.with( TemporalAdjusters.next( DayOfWeek.MONDAY ) ) ;
If you want to use the current date if it is a Monday, use TemporalAdjusters.nextOrSame.
Similar methods provide for previous day-of-week, as well: previous & previousOrSame.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Basically I have a date stored as text in this format: 16/09/2014 in SQLite Browser. I wonder is there any way to get the date after one day, one week, one month and one year of each records in the database using Java.
I retrieved and display the date retrieved from database in a listview:
viewHolder.txt_ddate.setText("Next Payment On: "
+ _recurlist.get(position).getRecurringStartDate().trim());
So I was thinking to use Java technique to get the dates I mentioned above. I have researched on this and found Documentation but I not sure how to implement it into my problem.
Any guides? Thanks in advance.
Use a Calendar object like in your example, which provides the add method.
String dateAsString = "16/09/2014";
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(formatter.parse(dateAsString));
c.add(Calendar.DAY_OF_MONTH, 1);
System.out.println("After one day: " + formatter.format(c.getTimeInMillis()));
c.add(Calendar.DAY_OF_MONTH, -1);
c.add(Calendar.WEEK_OF_YEAR, 1);
System.out.println("After one week: " + formatter.format(c.getTimeInMillis()));
c.add(Calendar.WEEK_OF_YEAR, -1);
c.add(Calendar.MONTH, 1);
System.out.println("After one month: " + formatter.format(c.getTimeInMillis()));
c.add(Calendar.MONTH, -1);
c.add(Calendar.YEAR, 1);
System.out.println("After one year: " + formatter.format(c.getTimeInMillis()));
c.add(Calendar.YEAR, -1);
Output:
After one day: 17/09/2014
After one week: 23/09/2014
After one month: 16/10/2014
After one year: 16/09/2015
With Joda-time:
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
LocalDate date = LocalDate.parse("16/09/2014", formatter);
System.out.println(date.toString(formatter));
System.out.println(date.plusDays(1).toString(formatter));
System.out.println(date.plusWeeks(1).toString(formatter));
System.out.println(date.plusMonths(1).toString(formatter));
System.out.println(date.plusYears(1).toString(formatter));
Output:
16/09/2014
17/09/2014
23/09/2014
16/10/2014
16/09/2015
Use Calendar api of Java/Android as follow:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date;
try {
date = sdf.parse(dateStr);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, 1); //add one day to your date
cal.add(Calendar.MONTH, 1); //add 1 month to your date
cal.add(Calendar.YEAR, 1); //add 1 year to current date
System.out.println(sdf.format(cal.getTimeInMillis()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Here is the example:
String strDate = "16/09/2014";
int noOfDays = 1;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(strDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, noOfDays);
tl;dr
LocalDate.parse(
"16/09/2014" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" )
)
.plusDays( 1 )
.format( DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) )
Details
Tip: Use date-time data types for date-time values. You should be using a date-oriented type to define your column in your database to store a date value rather than as text.
Tip # 2: When you do serialize a date value to text, use the standard ISO 8601 formats. These are sensible, practical, and sort chronologically when alphabetical.
Use the java.time classes rather than the troublesome old date-time classes that are now legacy. For Android, see bullets below.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate ld = LocalDate.parse( "16/09/2014" , f ) ;
LocalDate dayAfter = ld.plusDays( 1 ) ;
LocalDate weekAfter = ld.plusWeeks( 1 ) ;
LocalDate monthAfter = ld.plusMonths( 1 ) ;
LocalDate yearAfter = ld.plusYears( 1 ) ;
To generate a string in standard format, simply call toString.
String output = dayAfter.toString() ; // YYYY-MM-DD standard format.
2014-09-17
For other formats, use a DateTimeFormatter as seen above.
String output = dayAfter.format( f ) ;
17/09/2014
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
i have the input string as 2012-07-27 and i want the output as date but with the same format like 2012-07-27
my code is
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date today = df.parse("20-12-2005");
System.out.println("Today = " + df.format(today));
} catch (ParseException e) {
e.printStackTrace();
}
my output is
Fri Jul 27 00:00:00 IST 2012
but i want to return the date object like like 2012-07-26 23:59:59 instead of a string any help please
any help is very thank full
You can use your same SimpleDateFormat you used to parse the date, to format the date into a string.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = formatter.parse("2012-07-27");
System.out.println(date1); // prints Fri Jul 27 00:00:00 IST 2012
System.out.println(formatter.format(date1)); // prints 2012-07-26
First, I think it's important to note that System.out.println implicitly invokes the toString method of its argument. The argument must be an Object or a subclass of it. And Date is a subclass of Object. That being said, take a look at the 1.7 Date#toString implementation,
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == gcal.SUNDAY) {
index = 8;
}
convertToAbbr(sb, wtb[index]).append(' '); // EEE
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
TimeZone zi = date.getZone();
if (zi != null) {
sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz
} else {
sb.append("GMT");
}
sb.append(' ').append(date.getYear()); // yyyy
return sb.toString();
}
The string representation of a Date object is specified as EEE MMM dd HH:mm:ss zzz yyyy. This is exactly what you're seeing.
If you want to display a Date object in a different format, use the SimpleDateFormat class. Its sole purpose is to add flexibility to the way a Date object is represented as a string.
Also...
One possible, albeit ridiculous workaround would be to create your own wrapper class,
public class MyDate{
private final Date d;
private final SimpleDateFormat sdf;
public(Date d, SimpleDateFormat sdf){
this.d = d;
this.sdf = sdf;
}
// not recommended...should only be used for debugging purposes
#Override
public String toString(){
return sdf.format(d);
}
}
You must use another SimpleDateFormat with the desired output format (format())
You can get a String representation for a date using the same SimpleDateFormat. The format method does this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2012-07-27");
System.out.println(sdf.format(date1);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse("2012-07-27");
System.out.println(dateFormat.format(date));
There is no "format" property in java.util.Date. A Date instance is rather a simple object representing a moment in time (effectively, it's state is only defined by a unix timestamp it stores internally).
As others noted, use (for example) a SimpleDateFormat to print a Date instance as into a string.
tl;dr
LocalDate.parse( "2012-07-27" )
.toString()
2012-07-27
Details
The modern way is with the java.time classes.
The LocalDate class represents a date-only value without time-of-day and without time zone.
Standard format
Your input string format happens to comply with the ISO 8601 standard. The java.time classes use ISO 8601 formats by default when parsing/generating strings that represent date-time values. So no need to specify a formatting pattern at all.
LocalDate ld = LocalDate.parse( "2012-07-27" );
Do not conflate date-time objects with Strings representing their value. A date-time class/object can parse a string and generate a string, but the String is always a separate and distinct object.
String output = ld.toString();
2012-07-27
Custom format
If your input is non-standard, define a DateTimeFormatter to match.
String input = "20-12-2005" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
ld.toString(): 2012-07-27
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.