Converting date without time for different timezone - java

I store the date in UTC long and displayed in user timezone. But when I try to store only days without time it misleading to different dates.
Eg: Scheduling event on 05/06/2016 (06 May 2016). This date is unique for all regions without timezone. If user from GMT+5:30 timezone trying to add a event on 05/06/2016 then it ISO-8601 format is 2016-05-05T16:00:00.000Z and milliseconds is 1462464000000.
Then user from GMT timezone try to view this event. The date will be 05/05/2016 instead of 05/06/2016.
Is there any way to convert date without any timezone.

Java 8 provides the solution for your problem. If you can use Java 8, use java.time.LocalDate which represents only the date without the time. Store the long value returned by toEpochDay method.
A sample code is given below:
LocalDate date = LocalDate.of(2016, 5, 4);
// Store this long value
long noOfDays = date.toEpochDay(); // No of days from 1970-01-01
LocalDate newDate = LocalDate.ofEpochDay(noOfDays);
System.out.println(newDate); // 2016-05-04

Always store the whole timestap.
Whenever you want to display just convert the timestamp to whichever timezone you want to convert it to & display it.
These would help in conversions: (Time-stamp to Date or viseversa)
// timestamp to Date
long timestamp = 5607059900000; //Example -> in ms
Date d = new Date(timestamp );
// Date to timestamp
long timestamp = d.getTime();
//If you want the current timestamp :
Calendar c = Calendar.getInstance();
long timestamp = c.getTimeInMillis();
Refer : convert TimeStamp to Date in Java
You may display different date formats using SimpleDateFormat.
Eg:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainClass {
public static void main(String[] args) {
String pattern = "MM/dd/yyyy";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date = format.parse("12/31/2006");
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
// formatting
System.out.println(format.format(new Date()));
}
}

Related

Local to GMT and vice versa- Date and time conversion not working

I was trying to convert input date time to GMT+0 , later convert that back to its local time. Though local to GMT+0 conversion works, the later conversion-gmt to local fails!
Calendar cal=Calendar.getInstance();
cal.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
System.out.println("my inputTime:"+ sdf.format(cal.getTime()));
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("gmt+0 converted time:"+ sdf.format(cal.getTime()));
//now i want to get my local time from this converted gmt+0 standard time
String standdardTimeStr=sdf.format(cal.getTime());
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date date=sdf2.parse(standdardTimeStr);
Calendar cal2= Calendar.getInstance();
cal2.setTime(date);
System.out.println("standard input time:"+ sdf2.format(cal2.getTime()));
sdf2.setTimeZone(TimeZone.getTimeZone("GMT+6")); //or Asia/Dhaka
System.out.println("gmt+6 convertedtime:"+ sdf2.format(cal2.getTime()));
And this is my output:
my inputTime:2020-07-13T15:02:16.849
gmt+0 converted time:2020-07-13T09:02:16.849
standard input time:2020-07-13T09:02:16.849 //taking upper line as input-gmt+0
gmt+6 convertedtime:2020-07-13T09:02:16.849 //this date was supposed to be same as the first date
Please point out what am I doing wrong in coding or conceptually?
Just for the case you want a solution with a modern API, see this commented example:
public static void main(String[] args) {
// provide some fix example datetime String
String dateTime = "2020-05-08T13:57:06.345";
// create the two time zones needed before
ZoneId utc = ZoneId.of("UTC"); // UTC = GMT (+0)
ZoneId local = ZoneId.systemDefault(); // the zone of your JVM / system
/*
* then parse the String which doesn't contain information about a zone
* to an object that just knows date and time
*/
LocalDateTime ldt = LocalDateTime.parse(dateTime);
// and use that to create a zone-aware object with the same date and time
ZonedDateTime utcZdt = ZonedDateTime.of(ldt, utc);
// finally adjust its date and time by changing the zone
ZonedDateTime localZdt = utcZdt.withZoneSameInstant(local);
// then print both results
System.out.println(utcZdt + "\t==\t" + localZdt);
// and maybe try to use a different output format by defining a custom formatter
DateTimeFormatter gmtStyleDtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSO");
System.out.println(utcZdt.format(gmtStyleDtf)
+ "\t==\t" + localZdt.format(gmtStyleDtf));
}
which ouputs the following lines on my system (might be different on yours due to different time zones):
2020-05-08T13:57:06.345Z[UTC] == 2020-05-08T15:57:06.345+02:00[Europe/Berlin]
2020-05-08T13:57:06.345GMT == 2020-05-08T15:57:06.345GMT+2
EDIT:
Here's a possibility of doing the same thing but just dealing with offsets instead of time zones:
public static void main(String[] args) {
// provide some fix example datetime String
String dateTime = "2020-05-08T13:57:06.345";
// create the two offsets needed
ZoneOffset gmt = ZoneOffset.ofHours(0); // UTC = GMT (+0)
ZoneOffset gmtPlusSix = ZoneOffset.ofHours(6); // Asia/Dhaka ;-)
/*
* then parse the String which doesn't contain information about a zone
* to an object that just knows date and time
* NOTE: this just parses the String and does nothing else
*/
LocalDateTime justDateAndTime = LocalDateTime.parse(dateTime);
// and use that to create an offset-aware object with the same date and time
OffsetDateTime dateAndTimeAndGmtPlusSix = OffsetDateTime.of(justDateAndTime, gmtPlusSix);
// finally adjust its date and time by changing the offset keeping the instant
OffsetDateTime dateAndTimeInGmt = dateAndTimeAndGmtPlusSix.withOffsetSameInstant(gmt);
// then print both results
System.out.println(dateAndTimeAndGmtPlusSix + "\t==\t" + dateAndTimeInGmt);
// and maybe try to use a different output format by defining a custom formatter
DateTimeFormatter gmtStyleDtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSO");
System.out.println(dateAndTimeAndGmtPlusSix.format(gmtStyleDtf)
+ "\t==\t" + dateAndTimeInGmt.format(gmtStyleDtf));
}
Output:
2020-05-08T13:57:06.345+06:00 == 2020-05-08T07:57:06.345Z
2020-05-08T13:57:06.345GMT+6 == 2020-05-08T07:57:06.345GMT
Note that a Z is equivalent to an offset of GMT/UTC +0.
This way, you could create a method like
public static String convert(String datetime, int fromOffset, int toOffset) {
ZoneOffset fromZoneOffset = ZoneOffset.ofHours(fromOffset);
ZoneOffset toZoneOffset = ZoneOffset.ofHours(toOffset);
OffsetDateTime odt = LocalDateTime.parse(datetime).atOffset(fromZoneOffset);
return odt.withOffsetSameInstant(toZoneOffset)
.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
maybe handle invalid argument values, use it like this
public static void main(String[] args) {
String dateTime = "2020-05-08T13:57:06.345";
System.out.println(convert(dateTime, 6, 0)));
}
and receive the output
2020-05-08T07:57:06.345
I don't know why you're using a Calendar object. Javadoc of Calendar.getInstance() says:
The Calendar returned is based on the current time in the default time zone
Which means that calling cal.setTime(new Date()); is entirely redundant.
But, even worse than that, the following three are all the same:
// The very long way
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
Date date = cal.getTime();
// The long way
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
// The simple way
Date date = new Date();
A Date object always stores the date/time in UTC (GMT+0). Time zones are applied when a string is parsed, and when a string is formatted.
Parsing a string that doesn't specify a time zone offset will be parsed in the time zone of the SimpleDateFormat, which is the default time zone (aka the "local" time zone) unless otherwise specified, and the parsed value is converted to UTC for storage in a Date object.
Formatting a Date value to string will always use the time zone of the SimpleDateFormat.
Cleaning up the code in the question to not use Calendar, since that just obfuscates the issue, and commenting it to show what is going on, will answer your question of "point out what am I doing wrong in coding or conceptually":
Date now = new Date();
// Format the date in the local time zone
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
System.out.println("my inputTime:"+ sdf.format(now));
// Format the date in GMT time zone
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("gmt+0 converted time:"+ sdf.format(now));
// Format the date in GMT time zone (again), since the time ** ERROR MIGHT **
// zone of the formatter is still set to GMT ** BE HERE **
String standdardTimeStr = sdf.format(now);
// Parse the GMT date string as-if it is in local time zone ** OR MAYBE HERE **
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date date = sdf2.parse(standdardTimeStr); // Date value here is wrong
// Format the bad date value back to string in the same time
// zone, which means you get GMT time back, even though that
// is not the value of the `date` variable
System.out.println("standard input time:"+ sdf2.format(date));
// Do it again, same result, because the time zone is changed ** ERROR HERE **
// on the wrong formatter object
sdf.setTimeZone(TimeZone.getTimeZone("GMT+6")); //or Asia/Dhaka
System.out.println("gmt+6 convertedtime:"+ sdf2.format(date));
You are missing to take the string representation of time to convert it back to local. The modified code below will give an idea on the same:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class TimeZoneExample {
public static void main(String[] args) throws ParseException {
Calendar cal = Calendar.getInstance();
final Date currentTime = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
String timeInCurrentTimeZone = sdf.format(currentTime);
System.out.println("Time in current time zone: " + timeInCurrentTimeZone);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String timeInGMT = sdf.format(currentTime);
System.out.println("Time in GMT: " + timeInGMT);
// Now, take this time in GMT and parse the string -- this is the key, we want to work with the time which got
// displayed not the internal representation and that's why we will get the time from string!
Date parsedTime = sdf.parse(timeInGMT);
String parsedString = sdf.format(parsedTime);
System.out.println("(GMT) Time in Parsed String: " + parsedString); // here it will show up it in GMT as sdf is still set to GMT
// Change the zone for sdf
sdf.setTimeZone(TimeZone.getTimeZone("GMT+6")); // or Asia/Dhaka
System.out.println("(Local) Time in Parsed String: " + sdf.format(parsedTime)); // here it you will see the zone difference
}
}
Note: You will get better picture if you take fixed time instead of current time.

How to convert timestamp date to java.util date(yyyy-mm-dd) in java

I am getting date from Oracle is in Timestamp but I need to convert it in to this format 2020-02-17 (yyyy-mm-dd) format, but currently in postman I am receiving date as "2020-02-17T09:40:37.850+0000" in this format.
Any help on this would be really appreciated
You can easily convert a java.sql.Timestamp to a java.time.LocalDate and get a date String by formatting the LocalDate like this:
public static void main(String[] args) {
// just a timestamp stub that takes "now"
java.sql.Timestamp ts = java.sql.Timestamp.from(Instant.now());
// convert it to a modern date object
LocalDate justDate = ts.toLocalDateTime().toLocalDate();
// print it using a suitable formatter
System.out.println(justDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
The output (today) is
2020-02-17
You just need Java 8 or higher for this or import a backport library.
EDIT
If you don't need a String but a java.util.Date, do it with Instant only, like this:
public static void main(String[] args) {
// just a timestamp stub that takes "now"
Instant now = Instant.now();
Timestamp ts = Timestamp.from(now);
// create an Instant from the Timestamp
Instant timestampInstant = ts.toInstant();
// and then create a Date out from that Instant
java.util.Date creationDate = java.util.Date.from(now);
// do something with the Date here...
}
But please consider using java.time wherever possible, which might be in your domain class...
private String getZonedDateTime(String startTime){
// input -> startTime: 2020-02-17T09:40:37.850+0000
// output -> 2020-02-17
return ZonedDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"))
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
Just pass the Date String which you have and get it in what format you want.
That question is answered here
And what you want exactly, to display the date with that format or save with that format.
If you want display the date with (yyyy-mm-dd)
String dateFormated = new SimpleDateFormat("yyyy-MM-dd").format(myTimestamp);
System.out.println(dateFormated);
If you want save the date with that format you can try to do this:
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd);
String dateFormated = dateFormat.format(myTimestamp);
Date parsedDate = dateFormat.parse(dateFormated);
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
} catch(Exception e) {
}

Retrieving a DateTime Using resultset into a DateTime field [duplicate]

I'm retrieving a timestamp object from a database using ResultSet.getTimestamp(), but I'd like an easy way to get the date in the format of MM/DD/YYYY and the time in a format of HH:MM xx. I was tinkering around, it it looks as though I can do such by making use of the Date and/or DateTime objects within Java. Is that the best way to go, or do I even need to convert the timestamp to accomplish this? Any recommendations would be helpful.
....
while(resultSet.next()) {
Timestamp dtStart = resultSet.getTimestamp("dtStart");
Timestamp dtEnd = resultSet.getTimestamp("dtEnd");
// I would like to then have the date and time
// converted into the formats mentioned...
....
}
....
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(timestamp.getTime());
// S is the millisecond
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss:S");
System.out.println(simpleDateFormat.format(timestamp));
System.out.println(simpleDateFormat.format(date));
}
}
java.sql.Timestamp is a subclass of java.util.Date. So, just upcast it.
Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");
Using SimpleDateFormat and creating Joda DateTime should be straightforward from this point on.
java.time
Modern answer: use java.time, the modern Java date and time API, for your date and time work. Back in 2011 it was right to use the Timestamp class, but since JDBC 4.2 it is no longer advised.
For your work we need a time zone and a couple of formatters. We may as well declare them static:
static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");
Now the code could be for example:
while(resultSet.next()) {
ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
.atZoneSameInstant(zone);
// I would like to then have the date and time
// converted into the formats mentioned...
String dateFormatted = dtStart.format(dateFormatter);
String timeFormatted = dtStart.format(timeFormatter);
System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
}
Example output (using the time your question was asked):
Date: 09/20/2011; time: 18:13 -0400
In your database timestamp with time zone is recommended for timestamps. If this is what you’ve got, retrieve an OffsetDateTime as I am doing in the code. I am also converting the retrieved value to the user’s time zone before formatting date and time separately. As time zone I supplied America/Marigot as an example, please supply your own. You may also leave out the time zone conversion if you don’t want any, of course.
If the datatype in SQL is a mere timestamp without time zone, retrieve a LocalDateTime instead. For example:
ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
.atZone(zone);
No matter the details I trust you to do similarly for dtEnd.
I wasn’t sure what you meant by the xx in HH:MM xx. I just left it in the format pattern string, which yields the UTC offset in hours and minutes without colon.
Link: Oracle tutorial: Date Time explaining how to use java.time.
You can also get DateTime object from timestamp, including your current daylight saving time:
public DateTime getDateTimeFromTimestamp(Long value) {
TimeZone timeZone = TimeZone.getDefault();
long offset = timeZone.getOffset(value);
if (offset < 0) {
value -= offset;
} else {
value += offset;
}
return new DateTime(value);
}
LocalDateTime dtStart = rs.getTimestamp("dtStart").toLocalDateTime();
Converts this Timestamp object to a code LocalDateTime.
The conversion creates a code LocalDateTime that represents the
same year, month, day of month, hours, minutes, seconds and nanos
date-time value as this code Timestamp in the local time zone.
since 1.8

SimpleDateFormat returns wrong date value during parse

I m facing a problem:I want to get current time of GMT TimeZone in long.
I m using the following code as given below:
TimeZone timeZoneGmt = TimeZone.getTimeZone("GMT");
long gmtCurrentTime = getCurrentTimeInSpecificTimeZone(timeZoneGmt);
public static long getCurrentTimeInSpecificTimeZone(TimeZone timeZone) {
Calendar cal = Calendar.getInstance();
cal.setTimeZone(timeZone);
long finalValue = 0;
SimpleDateFormat sdf = new SimpleDateFormat(
"MMM dd yyyy hh:mm:ss:SSSaaa");
sdf.setTimeZone(timeZone);
Date finalDate = null;
String date = sdf.format(cal.getTime());
try {
finalDate = sdf.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finalValue = finalDate.getTime();
return finalValue;
}
As given in, above method
while formatting
String date = sdf.format(cal.getTime());
I m getting correct current time in GMT but as i do parsing by following code:
finalDate=sdf.parse(date);
Date got changed from current GMT time to 15:35:16 IST 2013 that is current time of my system.
I tried with Calendar as well in another way:
TimeZone timeZoneGmt=TimeZone.get("GMT");
Calendar calGmt = Calendar.getInstance();
calGmt.setTimeZone(timeZoneGmt);
long finalGmtValue = 0;
finalGmtValue = calGmt.getTimeInMillis();
System.out.println("Date......" + calGmt.getTime());
but still getting date as current time of my System Thu Jan 23 15:58:16 IST 2014 Not getting GMT current time.
You've misunderstood how Date works. A Date doesn't have a time zone - if you use Date.toString() you'll always see the default time zone. The long value in a Date is purely the number of milliseconds since the Unix epoch: it doesn't have any concept of time zone or calendar system.
If you want to represent a date and time in a particular time zone and calendar, use Calendar instead - but for getting "the current date and time as a long" you can just use System.currentTimeMillis(), which again does not have anything to do with the system time zone.
Additionally, even if you did want to do manipulation like this, you shouldn't be using string conversions. You're not conceptually performing any string conversions, so why introduce them?
If your aim is to display (as a string) the current date and time in a particular time zone, you should just use something like:
Date date = new Date(); // This will use the current time
SimpleDateFormat format = new SimpleDateFormat(...); // Pattern and locale
format.setTimeZone(zone); // The zone you want to display in
String formattedText = format.format(date);
When working with date and time APIs - particularly bad ones like the Java Calendar/Date API - it's very important that you understand exactly what each value in your system represents.

How to get previous date in java

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);

Categories