I am trying to get my calendar to print what day it is in dd/MM/yyyy format, but it just doesn't seem to work.
My code is:
SimpleDateFormat form = new SimpleDateFormat("dd/MM/yy", Locale.ENGLISH);
Date now = new Date("19/11/16");
form.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(form.format(now));
Calendar cal = Calendar.getInstance();
cal.setTime(now);
System.out.println(cal.get((Calendar.DAY_OF_WEEK)));
if(cal.get((Calendar.DAY_OF_WEEK)) < 7 || cal.get((Calendar.DAY_OF_WEEK)) > 1) {
System.out.println("It's a weekday");
}
else {
System.out.println("It's a weekend");
}
And the output is:
10/07/17
3
It's a weekday
Can anyone spot the issue?
The Date constructor you are calling is creating a Date with the wrong fields, to initialize your Date with your format parse the String. Like
Date now = form.parse("19/11/16");
Making sure to either catch (or rethrow) ParseException. With those two changes I then get
19/11/16
7
It's a weekday
Related
This question already has answers here:
Calendar date to yyyy-MM-dd format in java
(11 answers)
Closed 4 years ago.
I am encountering an issue which is related to Java Date Function.
I'm getting the date from Application (example: 6/5/18) which is in MM/DD/YY format. Now I need to do -2 from the date. I know how to do -2 from current system date using calendar object (see the below code).
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
String PastDate = dateFormat.format(cal.getTime());
info("Date is displayed as : "+ PastDate );
I'm not able to put the date which I'm getting from Application in this format. Can someone please help me? (Any other way to do it would also be fine)
I suggest you to use Java 8 compatible Date and Time types.
If you use java.time.LocalDate then this is the solution:
LocalDate.now().minusDays(2)
From your question, it seems that you have the challenge in dealing with formatting, and then doing the subtraction.
I would recommend Java Date and Time Apis for this purpose, using a formatter.
A junit method to achieve your requirement is given below
#Test
public void testDateFormatUsingJava8() {
CharSequence inputdateTxt = "6/5/18";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yy");
LocalDate inputDate = LocalDate.parse(inputdateTxt, formatter);
System.out.println(inputDate.minusDays(2L).format(formatter));
}
#Test
public void testDateCalenderUsingStringSplit() {
String inputdateTxt = "6/5/18";
String[] dateComponenets = inputdateTxt.split("//");
Calendar cal = Calendar.getInstance();
//Know where are the year month and date are stored.
cal.set(Integer.parseInt(dateComponenets[2]), Integer.parseInt(dateComponenets[0]), Integer.parseInt(dateComponenets[2]) );
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("M/d/yy");
String pastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ pastDate );
}
#Test
public void testDateCalenderUsingJavaUtilDateApi() throws ParseException {
String inputdateTxt = "6/5/18";
DateFormat dateFormat = new SimpleDateFormat("M/d/yy");
Date date = dateFormat.parse(inputdateTxt);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE,-2);
String pastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ pastDate );
The reason why I use "M/d/yy" is because your question does not pad the date and month fields in the input date with a zero. If there is a guarantee that you receive a padded value in the date and month field, using "MM/dd/yy" is suggested.
See the following answer for your reference :
DateTimeFormatterSupport for Single Digit Values
EDIT: considering the limitation to not use Java 8 Date Time APIs, I have added two other alternatives to solve the problem. The OP is free to choose any one of the solutions. Kept the Java 8 solution intact for information purposes.
Calendar cal = Calendar.getInstance();
cal.set(2018, 5, 6); // add this, setting data from the value you parsed
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
String PastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ PastDate);
Here is my code that convert string ("12/05/2015") from textView into date with the same format, and i want to get from that date its day of week.
String d1=((TextView)findViewById(R.id.tvDate2)).getText().toString();
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(d1);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar c = Calendar.getInstance();
c.setTime(convertedDate);
int day= c.get(Calendar.DAY_OF_WEEK);
System.out.println("day:"+day);
when i try 22/05/2015 (friday) it returns 4
but for 29/05/2015 (also friday) it returns 6
so where is the problem
You've mixed up the month and the day.
Either change your format to "dd/MM/yyyy" or change the inputted date string to "05/22/2015".
You have got your months and days flipped around in your format string. Try:
"dd/MM/yyyy"
This question already has answers here:
Adding days to a date in Java [duplicate]
(6 answers)
Closed 8 years ago.
String dt="2014-04-25";
I want to add n number of days in this date ... I have searched a lot but was not able to get any good working code....
I have tried SimpleDateFormat but it is not working so please help me with the code....
You can do it using joda time library
import org.joda.time;
String dt="2014-04-25";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime dateTime = formatter.parseDateTime(dt);
DateTime oneDayPlus = dateTime.plusDays(1);
String oneDayPlusString = oneDayPlus.toString(formatter); // This is "2014-04-26"
oneDayPlus would give you the object you need.
Again, this needs you to use an extra jar file, so use it if you can introduce adding a new library.
Remember String != Date they don't have anything in common (ok, exclude the fact that a string could represent a Date ok?)
If you want to add days to a String you could convert it to a Date and use normal APIs to add days to it.
And here we use SimpleDateFormat which is used to create from a patten string a date
String dt = "2014-04-25";
// yyyy-MM-dd
// year-month-day
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
try
{
Date date = format.parse(dt);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 5);
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
}
catch (ParseException e)
{
System.out.println("Wrong date");
}
yyyy-MM-dd is our patten which corrisponds to our string.
format.parse(dt);
wil try to create a Date object from the string we passed, if it fails it throw an ParseException. (If you want to check if it works just try to pass an invalid string)
Then we create a new Calendar instance and set the date to the date we created (which corrisponds to the the date in our string) and add five days to our date.. and here we go. Now calendar will refer to the 30-04-2014.
You can replace the
calendar.add(Calendar.DAY_OF_MONTH, 5);
with
calendar.add(Calendar.DAY_OF_MONTH, n);
If you want and it will add n days.
I am getting a hard coded date from the property file , which is of the format dd-MMM-yyyy.
Now i need to compare it with current date of same format. For that purpose , i cooked up this piece of code :
Date convDate = new Date();
Date currentFormattedDate = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
convDate = new SimpleDateFormat("dd-MMM-yyyy").parse("20-Aug-2013");
currentFormattedDate = new Date(dateFormat.format(currentFormattedDate));
if(currentFormattedDate.after(convDate) || currentFormattedDate.equals(convDate)){
System.out.println("Correct");
}else{
System.out.println("In correct");
}
But eclipse tells me that new Date has been depreciated. Does any one know of any alternative way of doing this ? I am going crazy over this. Thanks !
One of the way is to use the Calendar class and its after() , equals() and before() methods.
Calendar currentDate = Calendar.getInstance();
Calendar anotherDate = Calendar.getInstance();
Date convDate = new SimpleDateFormat("dd-MMM-yyyy").parse("20-Aug-2013");
anotherDate.setTime(convDate);
if(currentDate .after(anotherDate) ||
currentDate .equals(anotherDate)){
System.out.println("Correct");
}else{
System.out.println("In correct");
}
You can also use Jodatime library , see this SO answer.
You should use the Date(long) constructor:
Date convDate = new Date(System.currentTimeMillis());
This way you'll avoid the deprecation warning and will get a Date instance with the system time.
Date represents number of milliseconds since the epoch. Why not just use the Date returned from
Date currentFormattedDate = new Date();
?
I have a String Object in format yyyyMMdd.Is there a simple way to get a String with previous date in the same format?
Thanks
I would rewrite these answers a bit.
You can use
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
// Get a Date object from the date string
Date myDate = dateFormat.parse(dateString);
// this calculation may skip a day (Standard-to-Daylight switch)...
//oneDayBefore = new Date(myDate.getTime() - (24 * 3600000));
// if the Date->time xform always places the time as YYYYMMDD 00:00:00
// this will be safer.
oneDayBefore = new Date(myDate.getTime() - 2);
String result = dateFormat.format(oneDayBefore);
To get the same results as those that are being computed by using Calendar.
Here is how to do it without Joda Time:
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("yyyyMMdd");
// 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 = "20100316";
try {
// This will print 20100315
System.out.println(previousDateString(dateString));
} catch (ParseException e) {
System.out.println("Invalid date string");
e.printStackTrace();
}
}
}
You can use:
Calendar cal = Calendar.getInstance();
//subtracting a day
cal.add(Calendar.DATE, -1);
SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd");
String result = s.format(new Date(cal.getTimeInMillis()));
It's much harder than it should be in Java without library support.
You can parse the given String into a Date object using an instance of the SimpleDateFormat class.
Then you can use Calendar's add() to subtract one day.
Then you can use SimpleDateFormat's format() to get the formatted date as a String.
The Joda Time library a much easier API.
This is an old question, and most existing answers pre-date Java 8. Hence, adding this answer for Java 8+ users.
Java 8 introduced new APIs for Date and Time to replace poorly designed, and difficult to use java.util.Date and java.util.Calendar classes.
To deal with dates without time zones, LocalDate class can be used.
String dateString = "20200301";
// BASIC_ISO_DATE is "YYYYMMDD"
// See below link to docs for details
LocalDate date = LocalDate.parse(dateString, DateTimeFormatter.BASIC_ISO_DATE);
// get date for previous day
LocalDate previousDate = date.minusDays(1);
System.out.println(previousDate.format(DateTimeFormatter.BASIC_ISO_DATE));
// prints 20200229
Docs:
DateTimeFormatter.BASIC_ISO_DATE
LocalDate
use SimpleDateFormat to parse the String to Date, then subtract one day. after that convert the date to String again.
HI,
I want to get 20 days previous, to current date,
Calendar cal = Calendar.getInstance();
Calendar xdate = (Calendar)cal.clone();
xdate.set(Calendar.DAY_OF_YEAR, - 20);
System.out.println(" Current Time "+ cal.getTime().toString());
System.out.println(" X Time "+ xdate.getTime().toString());
I had some UN Expected result, When i tried on Jan 11th,
Current Time Tue Jan 11 12:32:16 IST 2011
X Time Sat Dec 11 12:32:16 IST 2010
Calendar cal = Calendar.getInstance();
Calendar xdate = (Calendar)cal.clone();
xdate.set(Calendar.DAY_OF_YEAR,cal.getTime().getDate() - 20 );
System.out.println(" Current Time "+ cal.getTime().toString());
System.out.println(" X Time "+ xdate.getTime().toString());
This code solved my Problem.
If you are willing to use the 3rd-party utility, Joda-Time, here is some example code using Joda-Time 2.3 on Java 7. Takes just two lines.
String dateAsString = "20130101";
org.joda.time.LocalDate someDay = org.joda.time.LocalDate.parse(dateAsString, org.joda.time.format.DateTimeFormat.forPattern("yyyymmdd"));
org.joda.time.LocalDate dayBefore = someDay.minusDays(1);
See the results:
System.out.println("someDay: " + someDay );
System.out.println("dayBefore: " + dayBefore );
When run:
someDay: 2013-01-01
dayBefore: 2012-12-31
This code assumes you have no time zone. Lacking a time zone is rarely a good thing, but if that's your case, that code may work for you. If you do have a time zone, use a DateTime object instead of LocalDate.
About that example code and about Joda-Time…
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 7 and earlier.
// http://www.joda.org/joda-time/
// Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
// JSR 310 was inspired by Joda-Time but is not directly based on it.
// http://jcp.org/en/jsr/detail?id=310
// By default, Joda-Time produces strings in the standard ISO 8601 format.
// https://en.wikipedia.org/wiki/ISO_8601
you can create a generic method which takes
- Date (String) (current date or from date),
- Format (String) (your desired fromat) and
- Days (number of days before(-ve value) or after(+ve value))
as input and return your desired date in required format.
following method can resolve this problem.
public String getRequiredDate(String date , String format ,int days){
try{
final Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat(format).parse(date));
cal.add(Calendar.DATE, days);
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.format(cal.getTime());
}
catch(Exception ex){
logger.error(ex.getMessage(), ex);
}
return date;
}
}
In Java 8 we can use directly for this purpose
LocalDate todayDate = LocalDate.now();
By default it provide the format of 2021-06-07, with the help of formater we can change this also
LocalDate previousDate = todayDate.minusDays(5);
Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.YEAR, -1);
Date dt2 = new Date(cal2.getTimeInMillis());
System.out.println(dt2);