-3

I have a String variable and i'd like turn it into a long variable.

String dtStart = "2018-04-25 20:09:55";
                    Date date = null;
                    long dateLong = 0;
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                    try {
                        date = format.parse(dtStart);


                        dateLong = date.getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

The variable dtStart musn't change the value,it says dateLong = 0, i'd like to turn this variable into long variable in dateLong.

Also i can turn dtStartd into "2010-10-15T09:27:37Z", this format, but i can't know how.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
All Might
  • 1
  • 4
  • 1
    Your `SimpleDateFormat` string does not really match your date string in `dtStart`, so I'm guessing the `parse` is failing. – chiliNUT May 12 '18 at 16:22
  • 1
    What is the time zone or offset-from-UTC intended by that input string? – Basil Bourque May 12 '18 at 18:40
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/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/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque May 12 '18 at 21:22
  • 1
    Welcome to Stack Overflow. For your next questions please be aware that it’s easier to help you when you tell us precisely what is the expected behaviour of your code and precisely how observed behaviour differs. In case of an error message or a stacktrace, please quote verbatim in the question and mark which line in the code the stacktrace refers to. Because you would like to get help and we would like to help you. – Ole V.V. May 14 '18 at 08:17

3 Answers3

1

2018-04-25 20:09:55 matches to yyyy-MM-dd HH:mm:ss

So you should use this format

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

yyyy is for year

MM is for month

dd is for date

HH is for 24 hour format time (hh for 12 hour)

mm is for minute

ss is for second

You can & should read about java string formats at link

Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
1

tl;dr

LocalDateTime.parse(                             // Parse string as a `LocalDateTime`. Lacking any time zone or offset-from-UTC means this is *not* a moment, *not* a point on the timeline.
    "2018-04-25 20:09:55".replace( " " , "T" )   // Alter input to comply with ISO 8601 standard format, used by default in the *java.time* classes.
)                                                // Returns a `LocalDateTime` object.
.atZone(                                         // Give context and meaning to our `LocalDateTime`, to determine a point on the timeline.
    ZoneId.of( "America/Montreal" )              // Always specify time zone using proper `Continent/Region` format, never 3-4 letter pseudo-zones such as `PST`, `CST`, `IST`.
)                                                // Returns a `ZonedDateTime` object.
.toInstant()                                     // 2018-04-26T00:09:55Z. Extract a UTC value, `Instant` object, from the `ZonedDateTime`.
.toEpochMilli()                                  // Ask for count of milliseconds from 1970-01-01T00:00Z to this moment. 

1524701395000

java.time

Alter your string input to comply with ISO 8601 standard.

String input = "2018-04-25 20:09:55".replace( " " , "T" ) ;

2018-04-25 20:09:55

Parse.

LocalDateTime ldt = LocalDateTime.parse( input ) ;

ldt.toString(): 2018-04-25T20:09:55

Apply the intended time zone, using a ZoneId to get a ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;

zdt.toString(): 2018-04-25T20:09:55-04:00[America/Montreal]

Extract a value in UTC, an Instant.

Instant instant = zdt.toInstant();

instant.toString(): 2018-04-26T00:09:55Z

Get the count of milliseconds since the first moment of 1970 UTC, 1970-01-01T00:00Z.

long millis = instant.toEpochMilli() ;

1524701395000

If that input string was intended for UTC rather than a time zone (your Question is not clear in that regard), use the same ideas as above, but switch to OffsetDateTime and ZoneOffset in place of ZonedDateTime and ZoneId.

LocalDateTime.parse(                     
    "2018-04-25 20:09:55".replace( " " , "T" )  
)                                        
.atOffset(                                     
    ZoneOffset.UTC                        // Using `ZoneOffset` rather than `ZoneId`. For UTC, we have the constant `ZoneOffset.UTC`. 
)                                         // Returns an `OffsetDateTime` object.                                            
.toInstant()                              // 2018-04-25T20:09:55Z
.toEpochMilli()  

Notice we get a different result than above, as 8 PM in UTC is a different moment than 8 PM in Montréal Québec.

1524686995000


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.

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

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

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

Your format string does not match the format used by the date string. Your date string is in this format:

yyyy-MM-dd HH:mm:ss

So

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

This also means that you don't know what the time zone of the date string is. Please take note of that.

Sweeper
  • 213,210
  • 22
  • 193
  • 313