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);
Related
This question already has answers here:
How to format date and time in Android?
(26 answers)
Closed 3 years ago.
I was building an android app and i was using Date class in my project to get the current date. I formatted the date with simpledateformatter and displayed it like dd-mm-yyyy (i.e. day month year) .
Now i also want to get the time in format of hh:MM:ss a (hours minutes seconds AM/PM)
As i was using date's instance i saw that it displays date and time also ( in default format). So i tried to fetch time from the date's instance.(let's say d is date class instance). I also found getTime() method of date class and performed d.getTime() but it returned me a long (which is duration from some fixed time from past to current time). Now i want time in desired format but this getTime() method is giving me long.
May you provide me some way on how to process this long value to get the desired format of time out of it. For example , d.getTime() return me some value( say 11233) and i want in format like this (11:33:22).
You can make that
private final String DATE_FORMAT = "dd.MM.yyyy HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
Date got = sdf.parse(date);
It returns Date with time to you
Use this snippet to get the date and time both.
public String currentDateTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss aa"); //it will give you the date in the formate that is given in the image
String datetime = dateformat.format(c.getTime()); // it will give you the date
return datetime;
}
Note: Take a look in the image .
Date().getTime() is providing you the timestamp
Change the format to your requirement like mm:hh:ss a
Kotlin
fun getDateTime():String {
val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault())
val date = Date()
return inputFormat.format(date.time)
}
JAVA
private String getDateTime(){
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
return format.format(new Date().getTime());
}
I need to save the current Date + 7 days in iso8601 format as following:
20161107T12:00:00+0000
Where the part after the "T" is fixed.
I tried the following:
Calendar exDate1 = Calendar.getInstance();
exDate1.add(Calendar.DATE , 7);
Date Date1 = exDate1.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDD");
String Date = sdf.format(Date1 + "T12:00:00+0000");
With no success.
Another way is using the new java.time-API in Java-8:
String result =
DateTimeFormatter.BASIC_ISO_DATE.format(
LocalDate.now(ZoneOffset.UTC).plusDays(7)
) + "T12:00:00+0000";
System.out.println(result); // 20161114T12:00:00+0000
Update due to your choice of timezone offset:
You tried to implicitly use the system timezone to determine the current local time but apply a fixed offset of UTC+0000. This is an inconsistent combination. If you apply such a zero offset then you should also determine the current date according to UTC+0000, not in your system timezone (ZoneId.systemDefault()).
The proposal of editor #Nim
Alternatively - the string above may not have the correct offset:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HH:mm:ssZ");
String date = LocalDate.now().plusDays(7).atTime(12, 0).atZone(ZoneId.systemDefault()).format(formatter);
would yield the result:
20161114T12:00:00+0100
which is probably not what you want. I also try to avoid the expression LocalDate.now() without any arguments because it hides the dependency on the system timezone.
use this 'yyyyMMdd'pattern
Calendar currentDate = Calendar.getInstance();
currentDate.add(Calendar.DATE, 7);
Date date = currentDate.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String formattedDate = sdf.format(date).concat("T12:00:00+0000");
This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 6 years ago.
In my Android app I have a string like this, String date = "2016-09-24T06:24:01Z";
I use this code to turn it into a nicer looking date format:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormat.setTimeZone(TimeZone.getDefault());
DateFormat formatted = new SimpleDateFormat(format);
Date result = dateFormat.parse(date);
dateString = formatted.format(result);
However it's not applying the timezone. I've tried setting it on both dateFormat and formatted and no matter what I do it still comes back with 6:24 AM.
Shouldn't TimeZone.getDefault() be looking at the timezone on the device running the app and adjusting the time accordingly?
As your are using java.util.date which have no Time Zone. It represent UTC/GMT no Time Zone offset. See below thing.
so change this line
dateFormat.setTimeZone(TimeZone.getDefault());
to this
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
or this
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
If you know the current time zone:
TimeZone tzone = TimeZone.getTimeZone("America/Los_Angeles");
tzone.setDefault(tzone);
If you do not know the current timezone:
Calendar cal = Calendar.getInstance();
long milliDiff = cal.get(Calendar.ZONE_OFFSET);
// Got local offset, now loop through available timezone id(s).
String [] ids = TimeZone.getAvailableIDs();
String name = null;
for (String id : ids) {
TimeZone tz = TimeZone.getTimeZone(id);
if (tz.getRawOffset() == milliDiff) {
// Found a match.
name = id;
break;
}
}
TimeZone tzone = TimeZone.getTimeZone(name);
tzone.setDefault(tzone);
I want to do something like:
Date date = new Date(); // current date
date = date - 300; // substract 300 days from current date and I want to use this "date"
How to do it?
Java 8 and later
With Java 8's date time API change, Use LocalDate
LocalDate date = LocalDate.now().minusDays(300);
Similarly you can have
LocalDate date = someLocalDateInstance.minusDays(300);
Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime
Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
Java 7 and earlier
Use Calendar's add() method
Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();
#JigarJoshi it's the good answer, and of course also #Tim recommendation to use .joda-time.
I only want to add more possibilities to subtract days from a java.util.Date.
Apache-commons
One possibility is to use apache-commons-lang. You can do it using DateUtils as follows:
Date dateBefore30Days = DateUtils.addDays(new Date(),-30);
Of course add the commons-lang dependency to do only date subtract it's probably not a good options, however if you're already using commons-lang it's a good choice. There is also convenient methods to addYears,addMonths,addWeeks and so on, take a look at the api here.
Java 8
Another possibility is to take advantage of new LocalDate from Java 8 using minusDays(long days) method:
LocalDate dateBefore30Days = LocalDate.now(ZoneId.of("Europe/Paris")).minusDays(30);
Simply use this to get date before 300 days, replace 300 with your days:
Date date = new Date(); // Or where ever you get it from
Date daysAgo = new DateTime(date).minusDays(300).toDate();
Here,
DateTime is org.joda.time.DateTime;
Date is java.util.Date
Java 8 Time API:
Instant now = Instant.now(); //current date
Instant before = now.minus(Duration.ofDays(300));
Date dateBefore = Date.from(before);
As you can see HERE there is a lot of manipulation you can do. Here an example showing what you could do!
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
//Add one day to current date.
cal.add(Calendar.DATE, 1);
System.out.println(dateFormat.format(cal.getTime()));
//Substract one day to current date.
cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println(dateFormat.format(cal.getTime()));
/* Can be Calendar.DATE or
* Calendar.MONTH, Calendar.YEAR, Calendar.HOUR, Calendar.SECOND
*/
With Java 8 it's really simple now:
LocalDate date = LocalDate.now().minusDays(300);
A great guide to the new api can be found here.
In Java 8 you can do this:
Instant inst = Instant.parse("2018-12-30T19:34:50.63Z");
// subtract 10 Days to Instant
Instant value = inst.minus(Period.ofDays(10));
// print result
System.out.println("Instant after subtracting Days: " + value);
I have created a function to make the task easier.
For 7 days after dateString: dateCalculate(dateString,"yyyy-MM-dd",7);
To get 7 days upto dateString: dateCalculate(dateString,"yyyy-MM-dd",-7);
public static String dateCalculate(String dateString, String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
try {
cal.setTime(s.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
}
cal.add(Calendar.DATE, days);
return s.format(cal.getTime());
}
You may also be able to use the Duration class. E.g.
Date currentDate = new Date();
Date oneDayFromCurrentDate = new Date(currentDate.getTime() - Duration.ofDays(1).toMillis());
You can easily subtract with calendar with SimpleDateFormat
public static String subtractDate(String time,int subtractDay) throws ParseException {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
cal.setTime(sdf.parse(time));
cal.add(Calendar.DATE,-subtractDay);
String wantedDate = sdf.format(cal.getTime());
Log.d("tag",wantedDate);
return wantedDate;
}
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);