How to get current date - two weeks date in Java? [duplicate] - java

This question already has answers here:
How to get the date 7 days earlier date from current date in Java [duplicate]
(6 answers)
Closed 8 years ago.
I have today's date in this string format 2014-05-08 and I needed to get the date of 2 weeks prior the currents date.
So the data I should be getting back is - 2014-04-24.
String currentDate= dateFormat.format(date); //2014-05-08
String dateBefore2Weeks = currentDate- 2 week;
But I am not sure how do I extract date of two weeks prior to current date in Java?

Use Calendar to modify your Date object:
//method created for demonstration purposes
public Date getDateBeforeTwoWeeks(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -14); //2 weeks
return calendar.getTime();
}
Use the method above in your code:
String currentDate= dateFormat.format(date); //2014-05-08
String dateBefore2Weeks = dateFormat.format(getDateBeforeTwoWeeks(date));

Java now has a pretty good built-in date library, java.time bundled with Java 8.
import java.time.LocalDate;
public class Foo {
public static void main(String[] args) {
System.out.println(LocalDate.parse("2014-05-08").minusWeeks(2));
// prints "2014-04-24"
}
}

Parse the date using a SimpleDateFormat into a Date object
Use a Calendar object to subtract 14 days from that date
Format the resulting date using the same SimpleDateFormat

worth having a look into joda-time api [http://joda-time.sourceforge.net/userguide.html].

Related

How to compare two dates in Java by incrementing Date? [duplicate]

This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
How to compare dates in Java? [duplicate]
(11 answers)
Closed 2 years ago.
How to compare two dates in Java by incrementing Date?
String dt = "2008-01-01"; // Start date
String et="2008-01-10";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
Date startDate=sdf.parse(dt);
Date endDate=sdf.parse(et);
Date incDate;
// dt is now the new date
do
{
System.out.println("hey i am called.....");
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime());
System.out.println("Incremet Date"+dt);
incDate=sdf.parse(dt);
}
while(endDate.compareTo(incDate)>=0);
first you should start using the newer classes like #TomStroemer pointed out.
I think you want to get the number of days between the two dates ?
LocalDate startDate = LocalDate.parse("2008-01-01");
LocalDate endDate = LocalDate.parse("2008-01-10");
Period period = Period.between(startDate, endDate);
System.out.println(period.getDays());
Should print 8 because there are 8 days between. Haven't tested that code.
See the following docs:
Period: https://docs.oracle.com/javase/8/docs/api/java/time/Period.html
LocalDate: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
And really provide more details.

How to decode the date in Android? - DATETIMESTAMP [duplicate]

This question already has answers here:
Android: Compare time in this format `yyyy-mm-dd hh:mm:ss` to the current moment
(5 answers)
Conversion of a date to epoch Java [duplicate]
(4 answers)
How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?
(16 answers)
Closed 2 years ago.
The following code gave me Datetimestamp as [ 2020-07-183 17:07:55.551 ]. The issue is with "Day" in Datetimestamp, which has three digits. How to format currentTimeMillis into the right format for day of month?
public String Datetimesetter(long currentTimeMillis, SimpleDateFormat dateFormat) {
dateFormat = new SimpleDateFormat("YYYY-MM-DD HH:MM:SS.SSS");
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(currentTimeMillis);
return dateFormat.format(calendar.getTime());
}
SOLUTION WHICH WORKED FOR ME:
Please visit this link.
This is for the case you are supporting Apps from API level 26 (native support of java.time) or you are willing / allowed to use a backport library of the same functionality.
Then you can use a correct / matching pattern (one that considers three-digit days) like this:
public static void main(String[] args) {
// mock / receive the datetime string
String timestamp = "2020-07-183 17:07:55.551";
// create a formatter using a suitable pattern (NOTE the 3 Ds)
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-DDD HH:mm:ss.SSS");
// parse the String to a LocalDateTime using the formatter defined before
LocalDateTime ldt = LocalDateTime.parse(timestamp, dtf);
// and print its default String representation
System.out.println(ldt);
}
which outputs
2020-07-01T17:07:55.551
So I guess the day of year no. 183 was actually July 1st.
your date format is incorrect
dateFormat = new SimpleDateFormat("YYYY-MM-DD HH:MM:SS.SSS");
change to this
dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS.SSS");

how to add days to date in java using simpledateformat and store output in string [duplicate]

This question already has answers here:
Adding days to a date in Java [duplicate]
(6 answers)
Closed 8 years ago.
Below is the code which generates the output as "9/2/2014"
public static void main (String[]args) throws ParseException
{
java.util.Date d = new Date();
SimpleDateFormat sd = new SimpleDateFormat("M/d/yyyy");
System.out.println(sd.format(d));
}
Now i need to add some n no of days and i wanted to get the output as 9/12/2014
please help me ...
If you want add month, or days to your date, use something like that:
public static Date addDays(Date date, int days)
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days); //minus number would decrement the days
return cal.getTime();
}
to add month use Calendar.Month
Calendar has methods for date manipulations. First create Calendar instance and set date to it
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
Then you can use calendar instance to add days like
calendar.add(Calendar.DATE,10);
to get date from calendar, use
System.out.println(calendar.getTime());

Converting a Date object to a calendar object [duplicate]

This question already has answers here:
Date object to Calendar [Java]
(8 answers)
Closed 6 years ago.
So I get a date attribute from an incoming object in the form:
Tue May 24 05:05:16 EDT 2011
I am writing a simple helper method to convert it to a calendar method, I was using the following code:
public static Calendar DateToCalendar(Date date )
{
Calendar cal = null;
try {
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString());
cal=Calendar.getInstance();
cal.setTime(date);
}
catch (ParseException e)
{
System.out.println("Exception :"+e);
}
return cal;
}
To simulate the incoming object I am just assigning the values within the code currently using:
private Date m_lastActivityDate = new Date();
However this is givin me a null pointer once the method reaches:
date = (Date)formatter.parse(date.toString());
Here's your method:
public static Calendar toCalendar(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
Everything else you are doing is both wrong and unnecessary.
BTW, Java Naming conventions suggest that method names start with a lower case letter, so it should be: dateToCalendar or toCalendar (as shown).
OK, let's milk your code, shall we?
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString());
DateFormat is used to convert Strings to Dates (parse()) or Dates to Strings (format()). You are using it to parse the String representation of a Date back to a Date. This can't be right, can it?
Just use Apache Commons
DateUtils.toCalendar(Date date)
it's so easy...converting a date to calendar like this:
Calendar cal=Calendar.getInstance();
DateFormat format=new SimpleDateFormat("yyyy/mm/dd");
format.format(date);
cal=format.getCalendar();

How to construct a Date from a String [duplicate]

This question already has answers here:
Date and calendar java
(2 answers)
Closed 5 years ago.
I have to compare two dates in if/else, the current date and the predefined date (let's say 1 Jan 2011). This was supposed to be simple, but I can't find the way to set the predefined date something like:
Java.util.Date date = new Date("2011-01-01");
How to compare two dates? I really don't know why it's so complicated to do.
Try:
import java.text.SimpleDateFormat;
import java.util.Date;
...
Date today = new Date();
Date predefined = new SimpleDateFormat("yyyy-MM-dd").parse("2011-01-01");
if(today.equals(predefined)) {
...
}
Use java.util.Calendar.
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, 2011);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.DATE, 1);
Date predefined = cal.getTime();
Date now = new Date();
if (now.after(predefined))
{
// do something
}
else
{
// do something else
}
or use JodaTime.
How to compare two dates? I really don't know why it's so complicated to do.
Because calendars/dates/times are really hard to get right, and the Java implementation of Date (and, in part Calendar) is an utter train wreck.
date.CompareTo(someOtherDate);
http://download.oracle.com/javase/1.4.2/docs/api/java/util/Date.html#compareTo(java.util.Date)

Categories

Resources