-3

This is my sample code

    String dt = "Oct 24 2019 12:00:00.000 AM UTC";
    String dt1="Oct 24 2019 11:59:59.000 PM UTC";
    SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS 
    aa zzz");
    Date date = df.parse(dt);
    Date date1 = df.parse(dt1);
    long epoch = date.getTime();
    long epoch1 = date1.getTime();
    System.out.println(epoch);
    System.out.println(epoch1);

Here specifying the AM and PM but its not taking the value for that and throwing the exception as

{"error_code":"INVALID_PARAMETER_VALUE","message":"Time range must have a start time earlier than the end time"}

How to specify AM/PM in the java code. How can I take yesterday's date and time for today in java code as an input to convert to epoch.

Divyashree R
  • 81
  • 1
  • 2
  • 9
  • I just ran your code snippet and everything works for me. – allkenang Oct 25 '19 at 07:03
  • 4
    Please don't use `Date` and `SimpleDateFormat` classes now. They have been replaced with much better classes. Look into [`LocalDateTime`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html) and [`DateTimeFormatter`](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) classes. – Mushif Ali Nawaz Oct 25 '19 at 07:09
  • 4
    FYI, the terribly flawed date-time classes such as [`java.util.Date`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/tutorial/datetime/TOC.html) classes built into Java 8 and later. – Basil Bourque Oct 25 '19 at 07:12
  • 3
    quick look at [documentation](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/text/SimpleDateFormat.html) reveals that `H`, uppercase, is used for "Hours (0-23)", while `h`, lowercase, for "Hours in am/pm(1-12)" – user85421 Oct 25 '19 at 07:13

2 Answers2

1

tl;dr

ZonedDateTime
.parse(
    "Oct 24 2019 12:00:00.000 AM UTC" ,
    DateTimeFormatter.ofPattern( "MMM d uuuu hh:mm:ss.SSS a z" ).withLocale( Locale.US ) 
)
.toInstant() 
.toEpochMilli() 

1571875200000

java.time

Two problems:

  • As commented by Heuberger, you are using incorrect formatting codes.
  • You are using terrible date-time classes supplanted years ago by the modern java.time classes.

Your inputs, renamed for clarity.

String inputStart = "Oct 24 2019 12:00:00.000 AM UTC";
String inputStop = "Oct 24 2019 11:59:59.000 PM UTC";

Define a formatting pattern to match your inputs.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM d uuuu hh:mm:ss.SSS a z" ).withLocale( Locale.US );

Parse inputs.

ZonedDateTime zdtStart = ZonedDateTime.parse( inputStart , f );
ZonedDateTime zdtStop = ZonedDateTime.parse( inputStop , f );

Calculate elapsed time. We should get one second less than 24 hours.

Duration d = Duration.between( zdtStart , zdtStop );

Apparently you want the count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z. First extract the building-block class, Instant, from each ZonedDateTime. An Instant represents a moment in UTC. This class lets you interrogate for the count since epoch. Note that java.time classes resolve to nanoseconds. So asking for milliseconds can result in data loss, ignoring any microseconds or nanoseconds.

Instant start = zdtStart.toInstant() ;
Instant stop = zdtStop.toInstant() ;

long millisStart = start.toEpochMilli() ;
long milliStop = stop.toEpochMilli() ;

Dump to console.

System.out.println( "zdtStart = " + zdtStart );
System.out.println( "zdtStop = " + zdtStop );
System.out.println( "d = " + d );

System.out.println( "start = " + start );
System.out.println( "stop = " + stop );

System.out.println( "millisStart = " + millisStart );
System.out.println( "milliStop = " + milliStop );

zdtStart = 2019-10-24T00:00Z[UTC]

zdtStop = 2019-10-24T23:59:59Z[UTC]

d = PT23H59M59S

start = 2019-10-24T00:00:00Z

stop = 2019-10-24T23:59:59Z

millisStart = 1571875200000

milliStop = 1571961599000


Table of date-time types in Java, both modern and legacy


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?

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

You need to use the following date format:

SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy hh:mm:ss.SSS a zzz",Locale.US);

For AM/PM Marker, 'a' is used. For reference

e.g.

import java.util.*;
import java.text.*;
public class Main
{
    public static void main(String[] args) {
        try{
            String dt = "Oct 24 2019 12:00:00.000 AM UTC";
            String dt1="Oct 24 2019 11:59:59.000 PM UTC";
            SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy hh:mm:ss.SSS a zzz",Locale.US);
            Date date = df.parse(dt);
            Date date1 = df.parse(dt1);
            long epoch = date.getTime();
            long epoch1 = date1.getTime();
            System.out.println(epoch);
            System.out.println(epoch1);  
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

output:

1571918400000                                                                                                                                                                      
1571918399000
Sahil Manchanda
  • 9,812
  • 4
  • 39
  • 89
  • You should also add second parameter to `new SimpleDateFormat` with value `Locale.US`, otherwise parsing may fail, since `Oct` would be an unknown month in most other languages. – Andreas Oct 25 '19 at 07:26
  • 2
    How can 1 second before midnight on 24th be 1 second before midnight on the 24th? There is 23 hours, 59 minutes, 59 seconds from midnight (start of day) to 1 second before midnight (end of day). When I run your code, I get `1571875200000` and `1571961599000` – Andreas Oct 25 '19 at 07:30