How to get previous date in java





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







13















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










share|improve this question




















  • 2





    Not a direct answer but take a look a Joda Time. It's a really good date/time library for Java - joda-time.sourceforge.net

    – Trevor Tippins
    Mar 16 '10 at 20:57


















13















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










share|improve this question




















  • 2





    Not a direct answer but take a look a Joda Time. It's a really good date/time library for Java - joda-time.sourceforge.net

    – Trevor Tippins
    Mar 16 '10 at 20:57














13












13








13


3






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










share|improve this question
















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







java date






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 1 '12 at 7:53









Raj

89482449




89482449










asked Mar 16 '10 at 20:52









SergSerg

5,96172745




5,96172745








  • 2





    Not a direct answer but take a look a Joda Time. It's a really good date/time library for Java - joda-time.sourceforge.net

    – Trevor Tippins
    Mar 16 '10 at 20:57














  • 2





    Not a direct answer but take a look a Joda Time. It's a really good date/time library for Java - joda-time.sourceforge.net

    – Trevor Tippins
    Mar 16 '10 at 20:57








2




2





Not a direct answer but take a look a Joda Time. It's a really good date/time library for Java - joda-time.sourceforge.net

– Trevor Tippins
Mar 16 '10 at 20:57





Not a direct answer but take a look a Joda Time. It's a really good date/time library for Java - joda-time.sourceforge.net

– Trevor Tippins
Mar 16 '10 at 20:57












9 Answers
9






active

oldest

votes


















13














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.






share|improve this answer





















  • 2





    You'll only run into problems when DST disturbs. Your code may then return the same day.

    – BalusC
    Mar 16 '10 at 22:19





















14














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





share|improve this answer





















  • 1





    Most of the code inside the try block doesn't even throw ParseException. You should limit its scope.

    – Steve Kuo
    Mar 16 '10 at 21:28











  • Makes for a slightly simpler example. That's the only reason I did it that way...

    – William Brendel
    Mar 16 '10 at 21:32











  • Thanks! The example was useful. I've used: DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); Calendar cal = new GregorianCalendar(); . . cal.setTime(dateFormat.parse(strDate)); cal.add(Calendar.DAY_OF_YEAR, -1); strDate= dateFormat.format( cal.getTime() );

    – Serg
    Mar 16 '10 at 21:57











  • Glad I could help!

    – William Brendel
    Mar 16 '10 at 21:58











  • Any specific reason you didn't use Calendar.getInstance()? To be on the safe side I would call calendar.clear() directly after constructing/getting it to avoid timezone clashes.

    – BalusC
    Mar 16 '10 at 22:19





















10














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





share|improve this answer































    5














    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.






    share|improve this answer































      4














      use SimpleDateFormat to parse the String to Date, then subtract one day. after that convert the date to String again.






      share|improve this answer































        2














        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.






        share|improve this answer































          0














          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





          share|improve this answer































            0














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





            share|improve this answer

































              -1














              Calendar cal2 = Calendar.getInstance();
              cal2.add(Calendar.YEAR, -1);
              Date dt2 = new Date(cal2.getTimeInMillis());
              System.out.println(dt2);





              share|improve this answer


























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2458049%2fhow-to-get-previous-date-in-java%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                9 Answers
                9






                active

                oldest

                votes








                9 Answers
                9






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                13














                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.






                share|improve this answer





















                • 2





                  You'll only run into problems when DST disturbs. Your code may then return the same day.

                  – BalusC
                  Mar 16 '10 at 22:19


















                13














                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.






                share|improve this answer





















                • 2





                  You'll only run into problems when DST disturbs. Your code may then return the same day.

                  – BalusC
                  Mar 16 '10 at 22:19
















                13












                13








                13







                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.






                share|improve this answer















                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.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 16 '10 at 22:53

























                answered Mar 16 '10 at 22:16









                vkraemervkraemer

                9,35412342




                9,35412342








                • 2





                  You'll only run into problems when DST disturbs. Your code may then return the same day.

                  – BalusC
                  Mar 16 '10 at 22:19
















                • 2





                  You'll only run into problems when DST disturbs. Your code may then return the same day.

                  – BalusC
                  Mar 16 '10 at 22:19










                2




                2





                You'll only run into problems when DST disturbs. Your code may then return the same day.

                – BalusC
                Mar 16 '10 at 22:19







                You'll only run into problems when DST disturbs. Your code may then return the same day.

                – BalusC
                Mar 16 '10 at 22:19















                14














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





                share|improve this answer





















                • 1





                  Most of the code inside the try block doesn't even throw ParseException. You should limit its scope.

                  – Steve Kuo
                  Mar 16 '10 at 21:28











                • Makes for a slightly simpler example. That's the only reason I did it that way...

                  – William Brendel
                  Mar 16 '10 at 21:32











                • Thanks! The example was useful. I've used: DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); Calendar cal = new GregorianCalendar(); . . cal.setTime(dateFormat.parse(strDate)); cal.add(Calendar.DAY_OF_YEAR, -1); strDate= dateFormat.format( cal.getTime() );

                  – Serg
                  Mar 16 '10 at 21:57











                • Glad I could help!

                  – William Brendel
                  Mar 16 '10 at 21:58











                • Any specific reason you didn't use Calendar.getInstance()? To be on the safe side I would call calendar.clear() directly after constructing/getting it to avoid timezone clashes.

                  – BalusC
                  Mar 16 '10 at 22:19


















                14














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





                share|improve this answer





















                • 1





                  Most of the code inside the try block doesn't even throw ParseException. You should limit its scope.

                  – Steve Kuo
                  Mar 16 '10 at 21:28











                • Makes for a slightly simpler example. That's the only reason I did it that way...

                  – William Brendel
                  Mar 16 '10 at 21:32











                • Thanks! The example was useful. I've used: DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); Calendar cal = new GregorianCalendar(); . . cal.setTime(dateFormat.parse(strDate)); cal.add(Calendar.DAY_OF_YEAR, -1); strDate= dateFormat.format( cal.getTime() );

                  – Serg
                  Mar 16 '10 at 21:57











                • Glad I could help!

                  – William Brendel
                  Mar 16 '10 at 21:58











                • Any specific reason you didn't use Calendar.getInstance()? To be on the safe side I would call calendar.clear() directly after constructing/getting it to avoid timezone clashes.

                  – BalusC
                  Mar 16 '10 at 22:19
















                14












                14








                14







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





                share|improve this answer















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






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 16 '10 at 22:38

























                answered Mar 16 '10 at 21:01









                William BrendelWilliam Brendel

                26.8k146777




                26.8k146777








                • 1





                  Most of the code inside the try block doesn't even throw ParseException. You should limit its scope.

                  – Steve Kuo
                  Mar 16 '10 at 21:28











                • Makes for a slightly simpler example. That's the only reason I did it that way...

                  – William Brendel
                  Mar 16 '10 at 21:32











                • Thanks! The example was useful. I've used: DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); Calendar cal = new GregorianCalendar(); . . cal.setTime(dateFormat.parse(strDate)); cal.add(Calendar.DAY_OF_YEAR, -1); strDate= dateFormat.format( cal.getTime() );

                  – Serg
                  Mar 16 '10 at 21:57











                • Glad I could help!

                  – William Brendel
                  Mar 16 '10 at 21:58











                • Any specific reason you didn't use Calendar.getInstance()? To be on the safe side I would call calendar.clear() directly after constructing/getting it to avoid timezone clashes.

                  – BalusC
                  Mar 16 '10 at 22:19
















                • 1





                  Most of the code inside the try block doesn't even throw ParseException. You should limit its scope.

                  – Steve Kuo
                  Mar 16 '10 at 21:28











                • Makes for a slightly simpler example. That's the only reason I did it that way...

                  – William Brendel
                  Mar 16 '10 at 21:32











                • Thanks! The example was useful. I've used: DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); Calendar cal = new GregorianCalendar(); . . cal.setTime(dateFormat.parse(strDate)); cal.add(Calendar.DAY_OF_YEAR, -1); strDate= dateFormat.format( cal.getTime() );

                  – Serg
                  Mar 16 '10 at 21:57











                • Glad I could help!

                  – William Brendel
                  Mar 16 '10 at 21:58











                • Any specific reason you didn't use Calendar.getInstance()? To be on the safe side I would call calendar.clear() directly after constructing/getting it to avoid timezone clashes.

                  – BalusC
                  Mar 16 '10 at 22:19










                1




                1





                Most of the code inside the try block doesn't even throw ParseException. You should limit its scope.

                – Steve Kuo
                Mar 16 '10 at 21:28





                Most of the code inside the try block doesn't even throw ParseException. You should limit its scope.

                – Steve Kuo
                Mar 16 '10 at 21:28













                Makes for a slightly simpler example. That's the only reason I did it that way...

                – William Brendel
                Mar 16 '10 at 21:32





                Makes for a slightly simpler example. That's the only reason I did it that way...

                – William Brendel
                Mar 16 '10 at 21:32













                Thanks! The example was useful. I've used: DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); Calendar cal = new GregorianCalendar(); . . cal.setTime(dateFormat.parse(strDate)); cal.add(Calendar.DAY_OF_YEAR, -1); strDate= dateFormat.format( cal.getTime() );

                – Serg
                Mar 16 '10 at 21:57





                Thanks! The example was useful. I've used: DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); Calendar cal = new GregorianCalendar(); . . cal.setTime(dateFormat.parse(strDate)); cal.add(Calendar.DAY_OF_YEAR, -1); strDate= dateFormat.format( cal.getTime() );

                – Serg
                Mar 16 '10 at 21:57













                Glad I could help!

                – William Brendel
                Mar 16 '10 at 21:58





                Glad I could help!

                – William Brendel
                Mar 16 '10 at 21:58













                Any specific reason you didn't use Calendar.getInstance()? To be on the safe side I would call calendar.clear() directly after constructing/getting it to avoid timezone clashes.

                – BalusC
                Mar 16 '10 at 22:19







                Any specific reason you didn't use Calendar.getInstance()? To be on the safe side I would call calendar.clear() directly after constructing/getting it to avoid timezone clashes.

                – BalusC
                Mar 16 '10 at 22:19













                10














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





                share|improve this answer




























                  10














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





                  share|improve this answer


























                    10












                    10








                    10







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





                    share|improve this answer













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






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 6 '13 at 7:07









                    Pratik Butani AndroidDevPratik Butani AndroidDev

                    31.1k27150275




                    31.1k27150275























                        5














                        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.






                        share|improve this answer




























                          5














                          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.






                          share|improve this answer


























                            5












                            5








                            5







                            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.






                            share|improve this answer













                            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.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 16 '10 at 20:56









                            brabsterbrabster

                            30.6k22125172




                            30.6k22125172























                                4














                                use SimpleDateFormat to parse the String to Date, then subtract one day. after that convert the date to String again.






                                share|improve this answer




























                                  4














                                  use SimpleDateFormat to parse the String to Date, then subtract one day. after that convert the date to String again.






                                  share|improve this answer


























                                    4












                                    4








                                    4







                                    use SimpleDateFormat to parse the String to Date, then subtract one day. after that convert the date to String again.






                                    share|improve this answer













                                    use SimpleDateFormat to parse the String to Date, then subtract one day. after that convert the date to String again.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Mar 16 '10 at 20:54









                                    William Witter da SilvaWilliam Witter da Silva

                                    318210




                                    318210























                                        2














                                        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.






                                        share|improve this answer




























                                          2














                                          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.






                                          share|improve this answer


























                                            2












                                            2








                                            2







                                            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.






                                            share|improve this answer













                                            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.







                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered Jan 11 '11 at 7:04









                                            kalyankalyan

                                            211




                                            211























                                                0














                                                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





                                                share|improve this answer




























                                                  0














                                                  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





                                                  share|improve this answer


























                                                    0












                                                    0








                                                    0







                                                    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





                                                    share|improve this answer













                                                    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






                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered Nov 6 '13 at 8:07









                                                    Basil BourqueBasil Bourque

                                                    118k30399562




                                                    118k30399562























                                                        0














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





                                                        share|improve this answer






























                                                          0














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





                                                          share|improve this answer




























                                                            0












                                                            0








                                                            0







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





                                                            share|improve this answer















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






                                                            share|improve this answer














                                                            share|improve this answer



                                                            share|improve this answer








                                                            edited Nov 22 '18 at 6:46

























                                                            answered Nov 22 '18 at 6:36









                                                            kamesh rathorekamesh rathore

                                                            13




                                                            13























                                                                -1














                                                                Calendar cal2 = Calendar.getInstance();
                                                                cal2.add(Calendar.YEAR, -1);
                                                                Date dt2 = new Date(cal2.getTimeInMillis());
                                                                System.out.println(dt2);





                                                                share|improve this answer






























                                                                  -1














                                                                  Calendar cal2 = Calendar.getInstance();
                                                                  cal2.add(Calendar.YEAR, -1);
                                                                  Date dt2 = new Date(cal2.getTimeInMillis());
                                                                  System.out.println(dt2);





                                                                  share|improve this answer




























                                                                    -1












                                                                    -1








                                                                    -1







                                                                    Calendar cal2 = Calendar.getInstance();
                                                                    cal2.add(Calendar.YEAR, -1);
                                                                    Date dt2 = new Date(cal2.getTimeInMillis());
                                                                    System.out.println(dt2);





                                                                    share|improve this answer















                                                                    Calendar cal2 = Calendar.getInstance();
                                                                    cal2.add(Calendar.YEAR, -1);
                                                                    Date dt2 = new Date(cal2.getTimeInMillis());
                                                                    System.out.println(dt2);






                                                                    share|improve this answer














                                                                    share|improve this answer



                                                                    share|improve this answer








                                                                    edited Dec 17 '12 at 9:54









                                                                    psubsee2003

                                                                    6,99174971




                                                                    6,99174971










                                                                    answered Dec 17 '12 at 9:50









                                                                    shah sanketshah sanket

                                                                    216212




                                                                    216212






























                                                                        draft saved

                                                                        draft discarded




















































                                                                        Thanks for contributing an answer to Stack Overflow!


                                                                        • Please be sure to answer the question. Provide details and share your research!

                                                                        But avoid



                                                                        • Asking for help, clarification, or responding to other answers.

                                                                        • Making statements based on opinion; back them up with references or personal experience.


                                                                        To learn more, see our tips on writing great answers.




                                                                        draft saved


                                                                        draft discarded














                                                                        StackExchange.ready(
                                                                        function () {
                                                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2458049%2fhow-to-get-previous-date-in-java%23new-answer', 'question_page');
                                                                        }
                                                                        );

                                                                        Post as a guest















                                                                        Required, but never shown





















































                                                                        Required, but never shown














                                                                        Required, but never shown












                                                                        Required, but never shown







                                                                        Required, but never shown

































                                                                        Required, but never shown














                                                                        Required, but never shown












                                                                        Required, but never shown







                                                                        Required, but never shown







                                                                        Popular posts from this blog

                                                                        Guess what letter conforming each word

                                                                        Port of Spain

                                                                        Run scheduled task as local user group (not BUILTIN)