5

I have written below code which is running, and giving output. But I'm not sure It's a right one.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = new Date();
sdf.setTimeZone(TimeZone.getTimeZone("GMT-7"));
String value = sdf.format(date);
System.out.println(value);
Date date2 = sdf.parse(value);
long result = date2.getTime();
System.out.println(result);
return result;

The above code what I'm trying is, I just need to get the current time of GMT time zone and convert it as epoch format which is gonna used in Oracle db.

Can someone tell me that format, and the above code is right?

ArrchanaMohan
  • 2,314
  • 4
  • 36
  • 84
  • 1
    I must admit, I don't understand what you are actually after, in particular looking at your code: Do you want to parse a date string and get the epoch millis, or do you want to format an epoch millis for a certain time zone? – Harald Aug 01 '18 at 19:32
  • 1
    I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Also your code is overly complicated and has a couple of bugs in it. – Ole V.V. Aug 05 '18 at 08:08
  • I think that this is what you need: [How do I get milliseconds from epoch (1970-01-01) in Java?](https://stackoverflow.com/questions/13731218/how-do-i-get-milliseconds-from-epoch-1970-01-01-in-java) – Ole V.V. Aug 05 '18 at 08:20

3 Answers3

6

First, you should not store time since the epoch as a timestamp in your database. Look into the date-time datatypes that your DMBS offers. In Oracle I think that a date column will be OK. For most other DBMS you would need a datetime column. timestamp and timestamp with timezone may be other and possibly even sounder options depending on your exact requirements.

However, taking your word for it: Getting the number of milliseconds since the epoch is simple when you know how:

    long millisecondsSinceEpoch = System.currentTimeMillis();
    System.out.println(millisecondsSinceEpoch);

This just printed:

1533458641714

The epoch is defined in UTC, so in this case we need to concern ourselves with no other time zones.

If you needed seconds rather than milliseconds, it’s tempting to divide by 1000. However, doing your own time conversions is a bad habit since the libraries already offers them, and using the appropriate library methods gives clearer, more explanatory and less error-prone code:

    long secondsSinceEpoch = Instant.now().getEpochSecond();
    System.out.println(secondsSinceEpoch);

1533458641

You said:

I just need to get the current time of GMT time zone…

Again taking your word:

    OffsetDateTime currentTimeInUtc = OffsetDateTime.now(ZoneOffset.UTC);
    System.out.println(currentTimeInUtc);
    long millisecondsSinceEpoch = currentTimeInUtc.toInstant().toEpochMilli();
    System.out.println(millisecondsSinceEpoch);
2018-08-05T08:44:01.719265Z
1533458641719

I know that GMT and UTC are not exactly the same, but for most applications they can be (and are) used interchangeably.

Can someone tell me (if) the above code is right?

When I ran your code just now, its output agreed with mine except the milliseconds were rounded down to whole thousands (whole seconds):

1533458641000

Your code has some issues, though:

  • You are using the old, long out-dated and poorly designed classes SimpleDateFormat, Date and TimeZone. The first in particular has a reputation for being troublesome. Instead we should use java.time, the modern Java date and time API.

  • Bug: In your format pattern string you are using lowercase hh for hour of day. hh is for hour within AM or PM, from 1 through 12, so will give you incorrect results at least half of the day. Uppercase HH is for hour of day.

  • Don’t use GMT-7 as a time zone. Use for example America/Los_Angeles. Of course select the time zone that makes sense for your situation. Edit: You said:

    I just want to specify the timezone for sanjose. GMT-7 is refer to sanjose current time.

    I believe many places are called San Jose. If you mean San Jose, California, USA, you are going to modify your program to use GMT-8 every time California goes back to standard time and opposite when summer time (DST) begins?? Miserable idea. Use America/Los_Angeles and your program will work all year.

  • Since you ask for time in the GMT time zone, what are you using GMT-7 for at all?

  • There is no point that I can see in formatting your Date into a string and parsing it back. Even if you did it correctly, the only result you would get would be to lose your milliseconds since there are no milliseconds in your format (it only has second precision; this also explained the rounding down I observed).

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • I just want to specify the timezone for sanjose. GMT-7 is refer to sanjose current time. – ArrchanaMohan Aug 06 '18 at 05:53
  • San Jose, California, USA, is in America/Los_Angeles time zone, which is using summer time (DST), that is, the offset from GMT is -8 sometimes and -7 sometimes. Using GMT-7 always is incorrect. Using America_Los_Angeles is always correct. Also see my edit. – Ole V.V. Dec 11 '20 at 20:25
3

Why not use Calendar class?

public long getEpochTime(){
    return Calendar.getInstance(TimeZone.getTimeZone("GMT-7")).getTime().getTime()/1000; //(  milliseconds to seconds)
}

It'll return the current Date's Epoch/Unix Timestamp.

Based on Harald's Comment:

 public static long getEpochTime(){
    return Clock.system(TimeZone.getTimeZone("GMT-7").toZoneId() ).millis()/1000;
}
Madhan Varadhodiyil
  • 2,086
  • 1
  • 14
  • 20
  • Let me try and I will update my comments. Many thanks for your response. – ArrchanaMohan Aug 01 '18 at 19:32
  • 6
    You should not use `Calendar` really these days, it has many idiosyncrasies and invites you to screw up seriously. Rather look at the new `java.time` package. – Harald Aug 01 '18 at 19:34
  • @Harald - sure I will try to use that java8 feature. Many thanks for your input. – ArrchanaMohan Aug 01 '18 at 19:56
  • 2
    The classes `Calendar` and `TimeZone` are long outdated, and even though `Calendar` tried to fix some of the issues with `Date`, it has turned out to be poorly designed. I recommend [java.time, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) instead. – Ole V.V. Aug 05 '18 at 08:25
  • 2
    Why not use `Calendar` class? Because it is a terrible class, of dreadful design, that was supplanted years ago by the *java.time* classes. Specifically, `ZonedDateTime`. – Basil Bourque Aug 05 '18 at 15:57
2

Here is a solution using the java.time API

ZonedDateTime zdt = LocalDateTime.now().atZone(ZoneId.of("GMT-7"));
long millis = zdt.toInstant().toEpochMilli();
gtgaxiola
  • 9,241
  • 5
  • 42
  • 64