Convert a date format in epochConvert Date String into Epoch in JavaJava - SimpleDateFormat formatter to return epoch time with millisecondsString (Date and Time) to Unix Timestamp in JavaJava Date timezone printing different timezones for different years, Workaround neededHow can I convert a date in YYYYMMDDHHMMSS format to epoch or unix time?add android calendar events using javaconvert date to timestamp UTCHow to convert a date time string to long (UNIX Epoch Time) in Java 8 (Scala)How to store RSS feeds in Android?Getting milliseconds from Date Time AndroidHow do I read / convert an InputStream into a String in Java?How to print a date in a regular format?Compare two dates with JavaScriptWhere can I find documentation on formatting a date in JavaScript?How do I get the current date in JavaScript?How to split a string in JavaHow to format a JavaScript dateJava string to date conversionConvert UTC Epoch to local dateHow do I convert a String to an int in Java?

If an enemy is just below a 10-foot-high ceiling, are they in melee range of a creature on the ground?

Why is Arya visibly scared in the library in S8E3?

How do you center multiple equations that have multiple steps?

If 1. e4 c6 is considered as a sound defense for black, why is 1. c3 so rare?

How to scale a verbatim environment on a minipage?

Was the ancestor of SCSI, the SASI protocol, nothing more than a draft?

Write to EXCEL from SQL DB using VBA script

Is it cheaper to drop cargo than to land it?

Did we get closer to another plane than we were supposed to, or was the pilot just protecting our delicate sensibilities?

Is balancing necessary on a full-wheel change?

Is Cola "probably the best-known" Latin word in the world? If not, which might it be?

Does higher resolution in an image imply more bits per pixel?

If Melisandre foresaw another character closing blue eyes, why did she follow Stannis?

Disabling Resource Governor in SQL Server

Any examples of headwear for races with animal ears?

Why is Thanos so tough at the beginning of "Avengers: Endgame"?

How can I close a gap between my fence and my neighbor's that's on his side of the property line?

Why are there synthetic chemicals in our bodies? Where do they come from?

Field Length Validation for Desktop Application which has maximum 1000 characters

Was Unix ever a single-user OS?

What happens if I start too many background jobs?

When do aircrafts become solarcrafts?

Unexpected email from Yorkshire Bank

What word means "to make something obsolete"?



Convert a date format in epoch


Convert Date String into Epoch in JavaJava - SimpleDateFormat formatter to return epoch time with millisecondsString (Date and Time) to Unix Timestamp in JavaJava Date timezone printing different timezones for different years, Workaround neededHow can I convert a date in YYYYMMDDHHMMSS format to epoch or unix time?add android calendar events using javaconvert date to timestamp UTCHow to convert a date time string to long (UNIX Epoch Time) in Java 8 (Scala)How to store RSS feeds in Android?Getting milliseconds from Date Time AndroidHow do I read / convert an InputStream into a String in Java?How to print a date in a regular format?Compare two dates with JavaScriptWhere can I find documentation on formatting a date in JavaScript?How do I get the current date in JavaScript?How to split a string in JavaHow to format a JavaScript dateJava string to date conversionConvert UTC Epoch to local dateHow do I convert a String to an int in Java?






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








50















I have a string with a date format such as



Jun 13 2003 23:11:52.454 UTC


containing millisec... which I want to convert in epoch.
Is there an utility in Java I can use to do this conversion?










share|improve this question






























    50















    I have a string with a date format such as



    Jun 13 2003 23:11:52.454 UTC


    containing millisec... which I want to convert in epoch.
    Is there an utility in Java I can use to do this conversion?










    share|improve this question


























      50












      50








      50


      11






      I have a string with a date format such as



      Jun 13 2003 23:11:52.454 UTC


      containing millisec... which I want to convert in epoch.
      Is there an utility in Java I can use to do this conversion?










      share|improve this question
















      I have a string with a date format such as



      Jun 13 2003 23:11:52.454 UTC


      containing millisec... which I want to convert in epoch.
      Is there an utility in Java I can use to do this conversion?







      java datetime date epoch






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 19 '16 at 4:35









      Ortomala Lokni

      24.3k786137




      24.3k786137










      asked Jul 14 '11 at 1:13









      user804979user804979

      298138




      298138






















          5 Answers
          5






          active

          oldest

          votes


















          84














          This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String:



          String str = "Jun 13 2003 23:11:52.454 UTC";
          SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
          Date date = df.parse(str);
          long epoch = date.getTime();
          System.out.println(epoch); // 1055545912454


          Date.getTime() returns the epoch time in milliseconds.






          share|improve this answer

























          • All good but don't throw Exception as such.

            – Anirudh
            Apr 10 '18 at 12:10












          • @Anirudh main wrapped removed...

            – Bohemian
            Apr 10 '18 at 18:56


















          20














          You can also use the new Java 8 API



          import java.time.ZonedDateTime;
          import java.time.format.DateTimeFormatter;

          public class StackoverflowTest
          public static void main(String args[])
          String strDate = "Jun 13 2003 23:11:52.454 UTC";
          DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss.SSS zzz");
          ZonedDateTime zdt = ZonedDateTime.parse(strDate,dtf);
          System.out.println(zdt.toInstant().toEpochMilli()); // 1055545912454




          The DateTimeFormatter class replaces the old SimpleDateFormat. You can then create a ZonedDateTime from which you can extract the desired epoch time.



          The main advantage is that you are now thread safe.



          Thanks to Basil Bourque for his remarks and suggestions. Read his answer for full details.






          share|improve this answer
































            5














            tl;dr



            ZonedDateTime.parse( 
            "Jun 13 2003 23:11:52.454 UTC" ,
            DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" )
            )
            .toInstant()
            .toEpochMilli()



            1055545912454




            java.time



            This Answer expands on the Answer by Lockni.



            DateTimeFormatter



            First define a formatting pattern to match your input string by creating a DateTimeFormatter object.



            String input = "Jun 13 2003 23:11:52.454 UTC";
            DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" );


            ZonedDateTime



            Parse the string as a ZonedDateTime. You can think of that class as: ( Instant + ZoneId ).



            ZonedDateTime zdt = ZonedDateTime.parse ( "Jun 13 2003 23:11:52.454 UTC" , f );



            zdt.toString(): 2003-06-13T23:11:52.454Z[UTC]




            Table of types of date-time classes in modern java.time versus legacy.



            Count-from-epoch



            I do not recommend tracking date-time values as a count-from-epoch. Doing so makes debugging tricky as humans cannot discern a meaningful date-time from a number so invalid/unexpected values may slip by. Also such counts are ambiguous, in granularity (whole seconds, milli, micro, nano, etc.) and in epoch (at least two dozen in by various computer systems).



            But if you insist you can get a count of milliseconds from the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00) through the Instant class. Be aware this means data-loss as you are truncating any nanoseconds to milliseconds.



            Instant instant = zdt.toInstant ();



            instant.toString(): 2003-06-13T23:11:52.454Z




            long millisSinceEpoch = instant.toEpochMilli() ; 



            1055545912454





            About java.time



            The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.



            To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.



            The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.



            You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.



            Where to obtain the java.time classes?




            • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.

              • Java 9 adds some minor features and fixes.



            • Java SE 6 and Java SE 7

              • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.



            • Android

              • Later versions of Android bundle implementations of the java.time classes.

              • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….


            The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.






            share|improve this answer
































              0














              Create Common Method to Convert String to Date format



              public static void main(String[] args) throws Exception 
              long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
              long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
              long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");


              private static long ConvertStringToDate(String dateString, String format)
              try
              return new SimpleDateFormat(format).parse(dateString).getTime();
              catch (ParseException e)
              return 0;






              share|improve this answer

























              • Don’t swallow exceptions. They have a meaning. Usually an important one.

                – Ole V.V.
                Jul 19 '17 at 20:30











              • I recommend staying away from the now long outdated date and time classes like SimpleDateFormat. In 2011, when the question was asked, I used them too. Not any more.

                – Ole V.V.
                Jul 19 '17 at 20:32



















              0














               String dateTime="15-3-2019 09:50 AM" //time should be two digit like 08,09,10 
              DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
              LocalDateTime zdt = LocalDateTime.parse(dateTime,dtf);
              LocalDateTime now = LocalDateTime.now();
              ZoneId zone = ZoneId.of("Asia/Kolkata");
              ZoneOffset zoneOffSet = zone.getRules().getOffset(now);
              long a= zdt.toInstant(zoneOffSet).toEpochMilli();
              Log.d("time","---"+a);


              you can get zone id form this a link!






              share|improve this answer


















              • 1





                Thank you for wanting to contribute. It’s not exactly the same question. I get java.time.format.DateTimeParseException: Text '15-3-2019 09:50 AM' could not be parsed at index 3. Finally the correct conversion is long a = LocalDateTime.parse(dateTime, dtf).atZone(zone).toInstant().toEpochMilli();.

                – Ole V.V.
                Mar 22 at 12:24











              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%2f6687433%2fconvert-a-date-format-in-epoch%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              5 Answers
              5






              active

              oldest

              votes








              5 Answers
              5






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              84














              This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String:



              String str = "Jun 13 2003 23:11:52.454 UTC";
              SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
              Date date = df.parse(str);
              long epoch = date.getTime();
              System.out.println(epoch); // 1055545912454


              Date.getTime() returns the epoch time in milliseconds.






              share|improve this answer

























              • All good but don't throw Exception as such.

                – Anirudh
                Apr 10 '18 at 12:10












              • @Anirudh main wrapped removed...

                – Bohemian
                Apr 10 '18 at 18:56















              84














              This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String:



              String str = "Jun 13 2003 23:11:52.454 UTC";
              SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
              Date date = df.parse(str);
              long epoch = date.getTime();
              System.out.println(epoch); // 1055545912454


              Date.getTime() returns the epoch time in milliseconds.






              share|improve this answer

























              • All good but don't throw Exception as such.

                – Anirudh
                Apr 10 '18 at 12:10












              • @Anirudh main wrapped removed...

                – Bohemian
                Apr 10 '18 at 18:56













              84












              84








              84







              This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String:



              String str = "Jun 13 2003 23:11:52.454 UTC";
              SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
              Date date = df.parse(str);
              long epoch = date.getTime();
              System.out.println(epoch); // 1055545912454


              Date.getTime() returns the epoch time in milliseconds.






              share|improve this answer















              This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String:



              String str = "Jun 13 2003 23:11:52.454 UTC";
              SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
              Date date = df.parse(str);
              long epoch = date.getTime();
              System.out.println(epoch); // 1055545912454


              Date.getTime() returns the epoch time in milliseconds.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Apr 10 '18 at 18:54

























              answered Jul 14 '11 at 1:25









              BohemianBohemian

              302k65432575




              302k65432575












              • All good but don't throw Exception as such.

                – Anirudh
                Apr 10 '18 at 12:10












              • @Anirudh main wrapped removed...

                – Bohemian
                Apr 10 '18 at 18:56

















              • All good but don't throw Exception as such.

                – Anirudh
                Apr 10 '18 at 12:10












              • @Anirudh main wrapped removed...

                – Bohemian
                Apr 10 '18 at 18:56
















              All good but don't throw Exception as such.

              – Anirudh
              Apr 10 '18 at 12:10






              All good but don't throw Exception as such.

              – Anirudh
              Apr 10 '18 at 12:10














              @Anirudh main wrapped removed...

              – Bohemian
              Apr 10 '18 at 18:56





              @Anirudh main wrapped removed...

              – Bohemian
              Apr 10 '18 at 18:56













              20














              You can also use the new Java 8 API



              import java.time.ZonedDateTime;
              import java.time.format.DateTimeFormatter;

              public class StackoverflowTest
              public static void main(String args[])
              String strDate = "Jun 13 2003 23:11:52.454 UTC";
              DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss.SSS zzz");
              ZonedDateTime zdt = ZonedDateTime.parse(strDate,dtf);
              System.out.println(zdt.toInstant().toEpochMilli()); // 1055545912454




              The DateTimeFormatter class replaces the old SimpleDateFormat. You can then create a ZonedDateTime from which you can extract the desired epoch time.



              The main advantage is that you are now thread safe.



              Thanks to Basil Bourque for his remarks and suggestions. Read his answer for full details.






              share|improve this answer





























                20














                You can also use the new Java 8 API



                import java.time.ZonedDateTime;
                import java.time.format.DateTimeFormatter;

                public class StackoverflowTest
                public static void main(String args[])
                String strDate = "Jun 13 2003 23:11:52.454 UTC";
                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss.SSS zzz");
                ZonedDateTime zdt = ZonedDateTime.parse(strDate,dtf);
                System.out.println(zdt.toInstant().toEpochMilli()); // 1055545912454




                The DateTimeFormatter class replaces the old SimpleDateFormat. You can then create a ZonedDateTime from which you can extract the desired epoch time.



                The main advantage is that you are now thread safe.



                Thanks to Basil Bourque for his remarks and suggestions. Read his answer for full details.






                share|improve this answer



























                  20












                  20








                  20







                  You can also use the new Java 8 API



                  import java.time.ZonedDateTime;
                  import java.time.format.DateTimeFormatter;

                  public class StackoverflowTest
                  public static void main(String args[])
                  String strDate = "Jun 13 2003 23:11:52.454 UTC";
                  DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss.SSS zzz");
                  ZonedDateTime zdt = ZonedDateTime.parse(strDate,dtf);
                  System.out.println(zdt.toInstant().toEpochMilli()); // 1055545912454




                  The DateTimeFormatter class replaces the old SimpleDateFormat. You can then create a ZonedDateTime from which you can extract the desired epoch time.



                  The main advantage is that you are now thread safe.



                  Thanks to Basil Bourque for his remarks and suggestions. Read his answer for full details.






                  share|improve this answer















                  You can also use the new Java 8 API



                  import java.time.ZonedDateTime;
                  import java.time.format.DateTimeFormatter;

                  public class StackoverflowTest
                  public static void main(String args[])
                  String strDate = "Jun 13 2003 23:11:52.454 UTC";
                  DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss.SSS zzz");
                  ZonedDateTime zdt = ZonedDateTime.parse(strDate,dtf);
                  System.out.println(zdt.toInstant().toEpochMilli()); // 1055545912454




                  The DateTimeFormatter class replaces the old SimpleDateFormat. You can then create a ZonedDateTime from which you can extract the desired epoch time.



                  The main advantage is that you are now thread safe.



                  Thanks to Basil Bourque for his remarks and suggestions. Read his answer for full details.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Apr 12 '17 at 9:53

























                  answered Jun 14 '15 at 13:43









                  Ortomala LokniOrtomala Lokni

                  24.3k786137




                  24.3k786137





















                      5














                      tl;dr



                      ZonedDateTime.parse( 
                      "Jun 13 2003 23:11:52.454 UTC" ,
                      DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" )
                      )
                      .toInstant()
                      .toEpochMilli()



                      1055545912454




                      java.time



                      This Answer expands on the Answer by Lockni.



                      DateTimeFormatter



                      First define a formatting pattern to match your input string by creating a DateTimeFormatter object.



                      String input = "Jun 13 2003 23:11:52.454 UTC";
                      DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" );


                      ZonedDateTime



                      Parse the string as a ZonedDateTime. You can think of that class as: ( Instant + ZoneId ).



                      ZonedDateTime zdt = ZonedDateTime.parse ( "Jun 13 2003 23:11:52.454 UTC" , f );



                      zdt.toString(): 2003-06-13T23:11:52.454Z[UTC]




                      Table of types of date-time classes in modern java.time versus legacy.



                      Count-from-epoch



                      I do not recommend tracking date-time values as a count-from-epoch. Doing so makes debugging tricky as humans cannot discern a meaningful date-time from a number so invalid/unexpected values may slip by. Also such counts are ambiguous, in granularity (whole seconds, milli, micro, nano, etc.) and in epoch (at least two dozen in by various computer systems).



                      But if you insist you can get a count of milliseconds from the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00) through the Instant class. Be aware this means data-loss as you are truncating any nanoseconds to milliseconds.



                      Instant instant = zdt.toInstant ();



                      instant.toString(): 2003-06-13T23:11:52.454Z




                      long millisSinceEpoch = instant.toEpochMilli() ; 



                      1055545912454





                      About java.time



                      The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.



                      To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.



                      The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.



                      You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.



                      Where to obtain the java.time classes?




                      • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.

                        • Java 9 adds some minor features and fixes.



                      • Java SE 6 and Java SE 7

                        • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.



                      • Android

                        • Later versions of Android bundle implementations of the java.time classes.

                        • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….


                      The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.






                      share|improve this answer





























                        5














                        tl;dr



                        ZonedDateTime.parse( 
                        "Jun 13 2003 23:11:52.454 UTC" ,
                        DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" )
                        )
                        .toInstant()
                        .toEpochMilli()



                        1055545912454




                        java.time



                        This Answer expands on the Answer by Lockni.



                        DateTimeFormatter



                        First define a formatting pattern to match your input string by creating a DateTimeFormatter object.



                        String input = "Jun 13 2003 23:11:52.454 UTC";
                        DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" );


                        ZonedDateTime



                        Parse the string as a ZonedDateTime. You can think of that class as: ( Instant + ZoneId ).



                        ZonedDateTime zdt = ZonedDateTime.parse ( "Jun 13 2003 23:11:52.454 UTC" , f );



                        zdt.toString(): 2003-06-13T23:11:52.454Z[UTC]




                        Table of types of date-time classes in modern java.time versus legacy.



                        Count-from-epoch



                        I do not recommend tracking date-time values as a count-from-epoch. Doing so makes debugging tricky as humans cannot discern a meaningful date-time from a number so invalid/unexpected values may slip by. Also such counts are ambiguous, in granularity (whole seconds, milli, micro, nano, etc.) and in epoch (at least two dozen in by various computer systems).



                        But if you insist you can get a count of milliseconds from the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00) through the Instant class. Be aware this means data-loss as you are truncating any nanoseconds to milliseconds.



                        Instant instant = zdt.toInstant ();



                        instant.toString(): 2003-06-13T23:11:52.454Z




                        long millisSinceEpoch = instant.toEpochMilli() ; 



                        1055545912454





                        About java.time



                        The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.



                        To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.



                        The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.



                        You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.



                        Where to obtain the java.time classes?




                        • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.

                          • Java 9 adds some minor features and fixes.



                        • Java SE 6 and Java SE 7

                          • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.



                        • Android

                          • Later versions of Android bundle implementations of the java.time classes.

                          • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….


                        The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.






                        share|improve this answer



























                          5












                          5








                          5







                          tl;dr



                          ZonedDateTime.parse( 
                          "Jun 13 2003 23:11:52.454 UTC" ,
                          DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" )
                          )
                          .toInstant()
                          .toEpochMilli()



                          1055545912454




                          java.time



                          This Answer expands on the Answer by Lockni.



                          DateTimeFormatter



                          First define a formatting pattern to match your input string by creating a DateTimeFormatter object.



                          String input = "Jun 13 2003 23:11:52.454 UTC";
                          DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" );


                          ZonedDateTime



                          Parse the string as a ZonedDateTime. You can think of that class as: ( Instant + ZoneId ).



                          ZonedDateTime zdt = ZonedDateTime.parse ( "Jun 13 2003 23:11:52.454 UTC" , f );



                          zdt.toString(): 2003-06-13T23:11:52.454Z[UTC]




                          Table of types of date-time classes in modern java.time versus legacy.



                          Count-from-epoch



                          I do not recommend tracking date-time values as a count-from-epoch. Doing so makes debugging tricky as humans cannot discern a meaningful date-time from a number so invalid/unexpected values may slip by. Also such counts are ambiguous, in granularity (whole seconds, milli, micro, nano, etc.) and in epoch (at least two dozen in by various computer systems).



                          But if you insist you can get a count of milliseconds from the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00) through the Instant class. Be aware this means data-loss as you are truncating any nanoseconds to milliseconds.



                          Instant instant = zdt.toInstant ();



                          instant.toString(): 2003-06-13T23:11:52.454Z




                          long millisSinceEpoch = instant.toEpochMilli() ; 



                          1055545912454





                          About java.time



                          The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.



                          To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.



                          The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.



                          You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.



                          Where to obtain the java.time classes?




                          • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.

                            • Java 9 adds some minor features and fixes.



                          • Java SE 6 and Java SE 7

                            • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.



                          • Android

                            • Later versions of Android bundle implementations of the java.time classes.

                            • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….


                          The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.






                          share|improve this answer















                          tl;dr



                          ZonedDateTime.parse( 
                          "Jun 13 2003 23:11:52.454 UTC" ,
                          DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" )
                          )
                          .toInstant()
                          .toEpochMilli()



                          1055545912454




                          java.time



                          This Answer expands on the Answer by Lockni.



                          DateTimeFormatter



                          First define a formatting pattern to match your input string by creating a DateTimeFormatter object.



                          String input = "Jun 13 2003 23:11:52.454 UTC";
                          DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" );


                          ZonedDateTime



                          Parse the string as a ZonedDateTime. You can think of that class as: ( Instant + ZoneId ).



                          ZonedDateTime zdt = ZonedDateTime.parse ( "Jun 13 2003 23:11:52.454 UTC" , f );



                          zdt.toString(): 2003-06-13T23:11:52.454Z[UTC]




                          Table of types of date-time classes in modern java.time versus legacy.



                          Count-from-epoch



                          I do not recommend tracking date-time values as a count-from-epoch. Doing so makes debugging tricky as humans cannot discern a meaningful date-time from a number so invalid/unexpected values may slip by. Also such counts are ambiguous, in granularity (whole seconds, milli, micro, nano, etc.) and in epoch (at least two dozen in by various computer systems).



                          But if you insist you can get a count of milliseconds from the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00) through the Instant class. Be aware this means data-loss as you are truncating any nanoseconds to milliseconds.



                          Instant instant = zdt.toInstant ();



                          instant.toString(): 2003-06-13T23:11:52.454Z




                          long millisSinceEpoch = instant.toEpochMilli() ; 



                          1055545912454





                          About java.time



                          The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.



                          To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.



                          The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.



                          You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.



                          Where to obtain the java.time classes?




                          • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.

                            • Java 9 adds some minor features and fixes.



                          • Java SE 6 and Java SE 7

                            • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.



                          • Android

                            • Later versions of Android bundle implementations of the java.time classes.

                            • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….


                          The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 22 at 20:02

























                          answered Oct 6 '16 at 20:21









                          Basil BourqueBasil Bourque

                          119k32405566




                          119k32405566





















                              0














                              Create Common Method to Convert String to Date format



                              public static void main(String[] args) throws Exception 
                              long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
                              long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
                              long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");


                              private static long ConvertStringToDate(String dateString, String format)
                              try
                              return new SimpleDateFormat(format).parse(dateString).getTime();
                              catch (ParseException e)
                              return 0;






                              share|improve this answer

























                              • Don’t swallow exceptions. They have a meaning. Usually an important one.

                                – Ole V.V.
                                Jul 19 '17 at 20:30











                              • I recommend staying away from the now long outdated date and time classes like SimpleDateFormat. In 2011, when the question was asked, I used them too. Not any more.

                                – Ole V.V.
                                Jul 19 '17 at 20:32
















                              0














                              Create Common Method to Convert String to Date format



                              public static void main(String[] args) throws Exception 
                              long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
                              long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
                              long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");


                              private static long ConvertStringToDate(String dateString, String format)
                              try
                              return new SimpleDateFormat(format).parse(dateString).getTime();
                              catch (ParseException e)
                              return 0;






                              share|improve this answer

























                              • Don’t swallow exceptions. They have a meaning. Usually an important one.

                                – Ole V.V.
                                Jul 19 '17 at 20:30











                              • I recommend staying away from the now long outdated date and time classes like SimpleDateFormat. In 2011, when the question was asked, I used them too. Not any more.

                                – Ole V.V.
                                Jul 19 '17 at 20:32














                              0












                              0








                              0







                              Create Common Method to Convert String to Date format



                              public static void main(String[] args) throws Exception 
                              long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
                              long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
                              long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");


                              private static long ConvertStringToDate(String dateString, String format)
                              try
                              return new SimpleDateFormat(format).parse(dateString).getTime();
                              catch (ParseException e)
                              return 0;






                              share|improve this answer















                              Create Common Method to Convert String to Date format



                              public static void main(String[] args) throws Exception 
                              long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
                              long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
                              long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");


                              private static long ConvertStringToDate(String dateString, String format)
                              try
                              return new SimpleDateFormat(format).parse(dateString).getTime();
                              catch (ParseException e)
                              return 0;







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Oct 22 '18 at 14:26









                              Shubham

                              2,02621528




                              2,02621528










                              answered Jun 7 '17 at 6:55









                              user1960808user1960808

                              1064




                              1064












                              • Don’t swallow exceptions. They have a meaning. Usually an important one.

                                – Ole V.V.
                                Jul 19 '17 at 20:30











                              • I recommend staying away from the now long outdated date and time classes like SimpleDateFormat. In 2011, when the question was asked, I used them too. Not any more.

                                – Ole V.V.
                                Jul 19 '17 at 20:32


















                              • Don’t swallow exceptions. They have a meaning. Usually an important one.

                                – Ole V.V.
                                Jul 19 '17 at 20:30











                              • I recommend staying away from the now long outdated date and time classes like SimpleDateFormat. In 2011, when the question was asked, I used them too. Not any more.

                                – Ole V.V.
                                Jul 19 '17 at 20:32

















                              Don’t swallow exceptions. They have a meaning. Usually an important one.

                              – Ole V.V.
                              Jul 19 '17 at 20:30





                              Don’t swallow exceptions. They have a meaning. Usually an important one.

                              – Ole V.V.
                              Jul 19 '17 at 20:30













                              I recommend staying away from the now long outdated date and time classes like SimpleDateFormat. In 2011, when the question was asked, I used them too. Not any more.

                              – Ole V.V.
                              Jul 19 '17 at 20:32






                              I recommend staying away from the now long outdated date and time classes like SimpleDateFormat. In 2011, when the question was asked, I used them too. Not any more.

                              – Ole V.V.
                              Jul 19 '17 at 20:32












                              0














                               String dateTime="15-3-2019 09:50 AM" //time should be two digit like 08,09,10 
                              DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
                              LocalDateTime zdt = LocalDateTime.parse(dateTime,dtf);
                              LocalDateTime now = LocalDateTime.now();
                              ZoneId zone = ZoneId.of("Asia/Kolkata");
                              ZoneOffset zoneOffSet = zone.getRules().getOffset(now);
                              long a= zdt.toInstant(zoneOffSet).toEpochMilli();
                              Log.d("time","---"+a);


                              you can get zone id form this a link!






                              share|improve this answer


















                              • 1





                                Thank you for wanting to contribute. It’s not exactly the same question. I get java.time.format.DateTimeParseException: Text '15-3-2019 09:50 AM' could not be parsed at index 3. Finally the correct conversion is long a = LocalDateTime.parse(dateTime, dtf).atZone(zone).toInstant().toEpochMilli();.

                                – Ole V.V.
                                Mar 22 at 12:24















                              0














                               String dateTime="15-3-2019 09:50 AM" //time should be two digit like 08,09,10 
                              DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
                              LocalDateTime zdt = LocalDateTime.parse(dateTime,dtf);
                              LocalDateTime now = LocalDateTime.now();
                              ZoneId zone = ZoneId.of("Asia/Kolkata");
                              ZoneOffset zoneOffSet = zone.getRules().getOffset(now);
                              long a= zdt.toInstant(zoneOffSet).toEpochMilli();
                              Log.d("time","---"+a);


                              you can get zone id form this a link!






                              share|improve this answer


















                              • 1





                                Thank you for wanting to contribute. It’s not exactly the same question. I get java.time.format.DateTimeParseException: Text '15-3-2019 09:50 AM' could not be parsed at index 3. Finally the correct conversion is long a = LocalDateTime.parse(dateTime, dtf).atZone(zone).toInstant().toEpochMilli();.

                                – Ole V.V.
                                Mar 22 at 12:24













                              0












                              0








                              0







                               String dateTime="15-3-2019 09:50 AM" //time should be two digit like 08,09,10 
                              DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
                              LocalDateTime zdt = LocalDateTime.parse(dateTime,dtf);
                              LocalDateTime now = LocalDateTime.now();
                              ZoneId zone = ZoneId.of("Asia/Kolkata");
                              ZoneOffset zoneOffSet = zone.getRules().getOffset(now);
                              long a= zdt.toInstant(zoneOffSet).toEpochMilli();
                              Log.d("time","---"+a);


                              you can get zone id form this a link!






                              share|improve this answer













                               String dateTime="15-3-2019 09:50 AM" //time should be two digit like 08,09,10 
                              DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
                              LocalDateTime zdt = LocalDateTime.parse(dateTime,dtf);
                              LocalDateTime now = LocalDateTime.now();
                              ZoneId zone = ZoneId.of("Asia/Kolkata");
                              ZoneOffset zoneOffSet = zone.getRules().getOffset(now);
                              long a= zdt.toInstant(zoneOffSet).toEpochMilli();
                              Log.d("time","---"+a);


                              you can get zone id form this a link!







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Mar 22 at 8:02









                              FlashFlash

                              13




                              13







                              • 1





                                Thank you for wanting to contribute. It’s not exactly the same question. I get java.time.format.DateTimeParseException: Text '15-3-2019 09:50 AM' could not be parsed at index 3. Finally the correct conversion is long a = LocalDateTime.parse(dateTime, dtf).atZone(zone).toInstant().toEpochMilli();.

                                – Ole V.V.
                                Mar 22 at 12:24












                              • 1





                                Thank you for wanting to contribute. It’s not exactly the same question. I get java.time.format.DateTimeParseException: Text '15-3-2019 09:50 AM' could not be parsed at index 3. Finally the correct conversion is long a = LocalDateTime.parse(dateTime, dtf).atZone(zone).toInstant().toEpochMilli();.

                                – Ole V.V.
                                Mar 22 at 12:24







                              1




                              1





                              Thank you for wanting to contribute. It’s not exactly the same question. I get java.time.format.DateTimeParseException: Text '15-3-2019 09:50 AM' could not be parsed at index 3. Finally the correct conversion is long a = LocalDateTime.parse(dateTime, dtf).atZone(zone).toInstant().toEpochMilli();.

                              – Ole V.V.
                              Mar 22 at 12:24





                              Thank you for wanting to contribute. It’s not exactly the same question. I get java.time.format.DateTimeParseException: Text '15-3-2019 09:50 AM' could not be parsed at index 3. Finally the correct conversion is long a = LocalDateTime.parse(dateTime, dtf).atZone(zone).toInstant().toEpochMilli();.

                              – Ole V.V.
                              Mar 22 at 12:24

















                              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%2f6687433%2fconvert-a-date-format-in-epoch%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

                              Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                              Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                              Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript