Get today midnight as milliseconds for given timezone java - java

I need to get the today midnight time as milliseconds. For example, today's date is 2020-03-20 and I convert this today midnight as milliseconds using the below code. If it works fine in my local environment, but the problem is when I deploy this code to the server, the server has UTC time zone, So even I pass the timezone, the milliseconds returned is wrong. After debugging I found out that this is happening due to parsing the Date, the date uses the default timeZone. I tried to set the timeZone in the Date, but the millisecond value returning is wrong even the date is 2020/03/20 00:00:00. For you to understand more below are some cases.
In the local Environment: Time Zone pass to method = "Asia/Colombo"
Date in milliseconds = 1584642600000
Converted date = Fri Mar 20 2020 00:00:00
In the Server Environment: Time Zone pass to method = "Asia/Colombo"
Date in milliseconds = 1584662400000
Converted date = Fri Mar 20 2020 05:30:00
Note that here Time Zone is the value I pass to my method parameter. I'm using java 8.
private static final String DATE_FORMAT = "yyyy/MM/dd 00:00:00";
private long getTMT(String timeZone) {
try {
ZoneId zoneId = ZoneId.of(timeZone);
ZonedDateTime currentZone = ZonedDateTime.now(zoneId);
ZonedDateTime zonedDateTime =
currentZone.withZoneSameInstant(zoneId);
DateTimeFormatter format =
DateTimeFormatter.ofPattern(DATE_FORMAT);
String formattedDateTime = zonedDateTime.format(format);
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
Date date = sdf.parse(formattedDateTime);
return date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
}
Hope I explained my question clearly, please let me know your answers/comments on this.
Thank you.

Formatting to string and then parsing from it is a horrible solution, especially since you also have to also construct all these parsers every time, and your format effectively has hacks in it.
There are simpler ways to both construct a midnight ZDT:
ZonedDateTime zdt = LocalDate.now(zoneId).atTime(LocalTime.MIDNIGHT).atZone(zoneID);
And then extracting the epoch-millis value from it:
long epoch = zdt.toInstant().toEpochMilli();
Alternatively, since you know that milliseconds and nanoseconds are always 0 at midnight, this is marginally faster:
long epoch = zdt.toEpochSecond() * 1000;
The second approach wouldn't work if your time is arbitrary, as it will always ignore milli-of-second value.

Related

Some dates cannot be converted correctly in Java to an epoch timestamps at the midnight of a specific timezone

This Java code, given a date as a string, is supposed to print the epoch timestamp for the same date at the midnight for the CET zone (supposing I'm not in the same zone).
public static void main(String[] args) throws ParseException {
String dateStr = "1995-06-06";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
formatter.setTimeZone(TimeZone.getTimeZone("CET"));
Date date = formatter.parse(dateStr);
Calendar c = new GregorianCalendar();
c.setTimeZone(TimeZone.getTimeZone("CET"));
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
System.out.println("Epoch timestamp = " + c.getTime().getTime());
}
If I run the above program I should get printed:
Epoch timestamp = 802389600000
And I can verify it's correct here:
https://www.epochconverter.com/timezones?q=802389600&tz=Europe%2FMalta
Now, that works for most of the dates. However, there are some bizarre dates like "1975-09-19", where it doesn't work. In fact, It generates 180313200000 as a timestamp, which gives 1am and not midnight:
https://www.epochconverter.com/timezones?q=180313200&tz=Europe%2FMalta
Can you explain why? What am I missing?
Time zone discrepancy
Your Java code uses CET, which is not really a time zone (for example because most of the areas where it’s used use CEST instead for most of the year). Java translates CET to Europe/Paris. France and Paris did not use summer time (DST) in 1975. It was reintroduced in March 1976.
Your link to the epoch converter specifies Malta time zone (Europe/Malta). Malta did use summer time in 1975: it was on CEST from 20 April to 21 September that year.
This explains the difference in your results.
In Java code
If you wanted Malta time:
String dateStr = "1975-09-19";
long epochTimestamp =
LocalDate
.parse(dateStr)
.atStartOfDay(ZoneId.of("Europe/Malta"))
.toInstant()
.toEpochMilli();
System.out.println("Epoch timestamp = " + epochTimestamp);
This prints:
Epoch timestamp = 180309600000
And the epoch converter that you linked to is happy to agree:
Conversion results (180309600)
180309600 converts to Friday September 19, 1975 00:00:00 (am) in
time zone Europe/Malta (CEST) The offset (difference to Greenwich
Time/GMT) is +02:00 or in seconds 7200. This date is in daylight
saving time.
In Java do use java.time, the modern Java date and time API, for your date and time work. It is so much nicer to work with compared to the old date and time classes like SimpleDateFormat, TimeZone, Date and Calendar. Also setting the hours, etc., to 0 is not the correct way to get the first moment of the day. There are cases where summer time begins at the start of the day, so the first moment of the day is 01:00:00. Java knows that, so the atStartOfDay method will give you the correct forst moment of the day in question.
And no matter if using outdated or modern classes always specify time zone in the region/city format, for example Europe/Paris or Europe/Malta. The three, four and five letter time zone abbreviations are often ambiguous and often not true time zones, so not to be relied on.
Links
Time Zone in Paris, Île-de-France, France
Time Zone in Valletta, Malta
Oracle tutorial: Date Time explaining how to use java.time.
There seems to be a difference concerning daylight saving time between your date examples.
If I use java.time (which should always be used since Java 8), I get results with different offsets:
"+02:00" for "1995-06-06" and
"+01:00" for "1975-09-19"
This is how I got the results:
public static void main(String[] args) {
// provide two sample dates
String workingDateStr = "1995-06-06";
String failingDateStr = "1975-09-19";
// and a formatter that parses the format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// then parse them to date objects that don't know about time or zone
LocalDate workingDate = LocalDate.parse(workingDateStr, dtf);
LocalDate failingDate = LocalDate.parse(failingDateStr, dtf);
/*
* then create an objects that are aware of time and zone
* by using the parsed dates, adding a time of 00:00:00 and a zone
*/
ZonedDateTime workingZdt = ZonedDateTime.of(workingDate, LocalTime.MIN, ZoneId.of("CET"));
ZonedDateTime failingZdt = ZonedDateTime.of(failingDate, LocalTime.MIN, ZoneId.of("CET"));
// finally, print different representations of the results
System.out.println(workingZdt + " ——> " + workingZdt.toInstant().toEpochMilli());
System.out.println(failingZdt + " ——> " + failingZdt.toInstant().toEpochMilli());
}
Output:
1995-06-06T00:00+02:00[CET] ——> 802389600000
1975-09-19T00:00+01:00[CET] ——> 180313200000
That means you might be better off using specific offsets instead of zones.
This issue could be due to the timing of the introduction of Daylight Saving Time in Malta, have a look at the following code and its output:
public static void main(String[] args) {
// provide two sample dates
String failingDateStr = "1975-09-19";
// and a formatter that parses the format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// then parse them to date objects that don't know about time or zone
LocalDate failingDate = LocalDate.parse(failingDateStr, dtf);
/*
* then create an objects that are aware of time and zone
* by using the parsed dates, adding a time of 00:00:00 and a zone
*/
ZonedDateTime failingZdt = ZonedDateTime.of(failingDate, LocalTime.MIN, ZoneId.of("CET"));
// add some years to 1975 and...
for (int year = 0; year < 4; year++) {
// ... print the different representations of the result
System.out.println(failingZdt.plusYears(year) + " ——> "
+ failingZdt.plusYears(year).toInstant().toEpochMilli());
}
}
Output:
1975-09-19T00:00+01:00[CET] ——> 180313200000
1976-09-19T00:00+01:00[CET] ——> 211935600000
1977-09-19T00:00+02:00[CET] ——> 243468000000
1978-09-19T00:00+02:00[CET] ——> 275004000000
This output indicates an introduction in 1977... Is that correct?

Not able to convert UTC to local time

I am writing a Java Code.I am able to convert the local time to UTC.But I am facing the problem when I want to convert it back to local time.The steps I am doing-
Getting milliseconds of the present.(DONE)
Converting present milliseconds(millisSinceEpoch) to present local time.(DONE)
Converting present milliseconds(millisSinceEpoch) to UTC time.(DONE)
Converting UTC time to UTC milliseconds.(DONE)
Convert UTC milliseconds to UTC Time.(DONE)
Convert UTC milliseconds to local time(IST)(Facing the problem here.....Getting the same UTC time here.Why is it not converting to Local time?).There is an answer where multiple date objects are created,But here I am not creating multiple date Objects and working only on milliseconds.My Code-
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.TimeZone;
public class TimeApiClass {
public static void main(String args[]) throws ParseException {
ZonedDateTime currentZone = ZonedDateTime.now();
//Getting milliseconds of the present
Instant instant=currentZone.toInstant();
long millisSinceEpoch=instant.toEpochMilli();
System.out.println("Not Converted to UTC-(Milliseconds-in local)");
System.out.println(millisSinceEpoch); //Output1->1579788244731
//Converting present milliseconds(millisSinceEpoch) to present local time
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS ");
String str3=sdf3.format(new Date(millisSinceEpoch));
System.out.println("Local Time-Not Converted to UTC-(Present local time)");
System.out.println(str3); //2020/01/23 19:34:04.731
//Converting present milliseconds(millisSinceEpoch) to UTC time
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS ");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String str=sdf.format(new Date(millisSinceEpoch));
System.out.println("UTC time-Local time Converted to UTC(unrequired time format)-");
System.out.println(str);// str contains 2020/01/22 13:22:55 UTC //Output3 ->2020/01/23 14:04:04.731
System.out.println("-----------------------------------------------------------------------------------------");
//Converting UTC time to UTC milliseconds
String myDate = str; // myDate and str contains 2020/01/22 10:08:42
SimpleDateFormat sdff = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS ");
Date date = sdff.parse(myDate);
long millis = date.getTime();
System.out.println("Converted to milliseconds(Now its in required format in UTC milliseconds)");
System.out.println(millis); //Output4 ->1579749867000
//Convert UTC milliseconds to UTC Time
DateFormat simple = new SimpleDateFormat(" yyyy/MM/dd HH:mm:ss.SSS");
Date result=new Date(millis);
System.out.println("Converting UTC milliseconds back to date/time format-");
System.out.println(simple.format(result));
//Convert UTC milliseconds to local time(IST)
Date dateee=new Date(millis); //Facing the problem here.....Getting the same UTC time here.Why is it not converting to Local time?
DateFormat format=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
format.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
System.out.println("lllllllllllllllllllllllll");
System.out.println(format.format(dateee));
//Converting UTC time to IST time
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS ");
sdf2.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
String istTime=sdf2.format(new Date(millis));
System.out.println("Now converting UTC millis to IST format->");
System.out.println(istTime); //Output5 ->2020/01/23 08:54:27 IST
//Converting IST time to milliseconds,here I am facing the problem.My output has to give the local milliseconds as I am passing ISTtime here,but its giving me UTC milliseconds,Which I dont want.
Date date66=sdf2.parse(istTime);
long finalMillis=date66.getTime();
System.out.println("Now converting IST to IST milliseconds:");
System.out.println(finalMillis); //Output6 ->1579749867000
}
}
//1579613838087
tl;dr
Convert a ZonedDateTime into a different time zone by ZonedDateTime.withZoneSameInstant(ZoneId)
You are not well advised to use java.util.SimpleDateFormat for operations on dates and times and your code shows partial use of java.time, which means you can just switch to java.time entirely. For formatting, use a java.time.format.DateTimeFormatter.
See this example:
public static void main(String[] args) {
// get the current instant
Instant instant = Instant.now();
// and convert it to a datetime object representing date and time in UTC
ZonedDateTime ofInstant = ZonedDateTime.ofInstant(instant, ZoneId.of("UTC"));
// print it
System.out.println("Now from Instant in UTC:\t"
+ ofInstant.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
// you can have a shorter way: current moment in your system's time zone
ZonedDateTime nowHere = ZonedDateTime.now();
// or in UTC
ZonedDateTime utcNow = ZonedDateTime.now(ZoneId.of("UTC"));
// print them both
System.out.println("Now in my (system's) time zone:\t"
+ nowHere.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
System.out.println("Now in UTC:\t\t\t"
+ utcNow.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
// then format the UTC datetime back to the one your system has
ZonedDateTime backFromUtc = utcNow.withZoneSameInstant(ZoneId.systemDefault());
// and print that one, too
System.out.println("Back from UTC:\t\t\t"
+ backFromUtc.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
}
The output something like:
Now from Instant in UTC: 2020-01-23T15:44:11.921Z[UTC]
Now in my (system's) time zone: 2020-01-23T16:44:12.091+01:00[Europe/Berlin]
Now in UTC: 2020-01-23T15:44:12.091Z[UTC]
Back from UTC: 2020-01-23T16:50:52.194+01:00[Europe/Berlin]
Why is it not converting to Local time?
Where it goes wrong for you: The string myDate is in UTC, but (1) there is no indication of UTC in the string, and (2) you are parsing it using the formatter sdff, but this formatter is not using UTC (it is using your default time zone, India Standard Time). Therefore you are getting a wrong result from parsing.
There may be another misunderstanding: The epoch is one specific point in time regardless of time zone. Therefore milliseconds since the epoch are the same in all time zones. So the first sign of a problem is probably when your program is printing two different millisecond values. If the millisecond values were supposed to denote the same point in time, you should see the same value both times.
All of this said, deHaar is correct in the other answer that you should stay away from all of DateFormat, SimpleDateFormat, Date and TimeZone. All of those classes are poorly designed and long outdated. I think that your use of the mentioned classes have contributed quite much to making your code more complicated than it had needed to be.
Edit:
So you are telling me to not use DateFormat,SimpleDateFormat and
TimeZone.So can you please suggest as to which class I should be
ideally using?
You are already on the good track when using Instant and ZonedDateTime from java.time, the modern Java date and time API. This API offers all the functionality you need and is so much nicer to work with, so I suggest that you stick to it. Other java.time classes that you will probably find useful include ZoneId (instead of TimeZone) and DateTimeFormatter (instead of SimpleDateFormat and DateFormat). For more see the tutorial and/or the documentation. I will add links at the bottom later.
To parse a UTC string into milliseconds since the epoch:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss.SSS");
String utcString = "2020/01/22 13:22:55.731";
long millisSinceEpoch = LocalDateTime.parse(utcString, formatter)
.atOffset(ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
System.out.println(millisSinceEpoch);
1579699375731
Or if your real goal was to convert it to local time in India:
ZoneId indiaStandardTime = ZoneId.of("Asia/Kolkata");
ZonedDateTime timeInIndia = LocalDateTime.parse(utcString, formatter)
.atOffset(ZoneOffset.UTC)
.atZoneSameInstant(indiaStandardTime);
System.out.println(timeInIndia);
2020-01-22T18:52:55.731+05:30[Asia/Kolkata]
I am first telling Java to interpret the string in UTC, next to convert it to IST.
Links
Oracle tutorial: Date Time explaining how to use java.time.
java.time package documentation

My question is about converting epoch millisecond from date in groovy

I am generating epoch timestamp in milliseconds with the following code and it works (verified with https://www.epochconverter.com/). However, when we are setting timezone with JVM option -Duser.timezone=America/Toronto then for some historical dates time offset is differ by one hour. i.e Date=1950-11-19 (yyyy-MM-dd) correct epoch milliseconds -603313200000 (Sunday, November 19, 1950 12:00:00 AM GMT-05:00) but when timezone is set with JVM options value is -603316800000 and Epoch converted shows Saturday, November 18, 1950 11:00:00 PM GMT-05:00. I have used joda time lib with JDK 10
def static Long getEpochTimeStampInMilliSeconds(String simpleDate, String dateFormat) {
Long retVal = null
try {
org.joda.time.format.DateTimeFormatter fmt = DateTimeFormat.forPattern(dateFormat)
DateTimeZone dtz2 = DateTimeZone.forID("America/Toronto")
DateTime parsedDateTime = DateTime.parse(simpleDate, fmt).withZone(dtz2)
retVal = parsedDateTime.getMillis()
} catch (Exception e) {
retVal = null
}
return retVal
}
date format is : "yyyy-MM-dd"
You need to parse with the correct time zone, so instead of calling dateTime.withZone(...) after parsing is done, you need to call dateTimeFormatter.withZone(...) before parsing with the formatter.
If the default time zone, as set by the user.timezone system property is America/Toronto, then the parsed DateTime value is already in that time zone, and dateTime.withZone(...) will do nothing.
If the default time zone is something else, then the parsed DateTime value is in that time zone, which would be a different UTC epoch millisecond value. Calling dateTime.withZone(...) will change the time zone, and hence the time value, but will not change the UTC epoch millisecond value.
def dtz2 = org.joda.time.DateTimeZone.forID("America/Toronto")
def fmt = org.joda.time.format.DateTimeFormat.forPattern(dateFormat).withZone(dtz2)
retVal = org.joda.time.DateTime.parse(simpleDate, fmt).getMillis()
UPDATE
From comment:
I am receiving -603316800000 for 1950-11-19 for all scenario but correct value is -603313200000
Lets test which value is correct, using Java-Time API:
ZoneId zone = ZoneId.of("America/Toronto");
System.out.println(Instant.ofEpochMilli(-603316800000L));
System.out.println(Instant.ofEpochMilli(-603316800000L).atZone(zone));
System.out.println(Instant.ofEpochMilli(-603313200000L));
System.out.println(Instant.ofEpochMilli(-603313200000L).atZone(zone));
Output
1950-11-19T04:00:00Z
1950-11-19T00:00-04:00[America/Toronto] ⬅ Correct value
1950-11-19T05:00:00Z
1950-11-19T01:00-04:00[America/Toronto]
As you can see, the value you get (-603316800000) is the correct value for 1950-11-19 at midnight, Toronto time.
You get offset -04:00 for Toronto, because in 1950, DST lasted until Sun, Nov 26 at 2:00 am (see https://www.timeanddate.com/time/zone/canada/toronto), so the offset is correct for Eastern Daylight Time (EDT).
Don't know why you think -603313200000 is the correct value, but it is not.

Covert date time from one zone to another

This is continuation to one of my previous question where I am not able to parse the date which is resolved now. In the below code, I have a date string and I know the time zone for the date string even though the string itself doesn't contain it. Then I need to convert the date into EST time zone.
String clientTimeZone = "CST6CDT";
String value = "Dec 29 2014 11:36PM";
value=StringUtils.replace(value, " ", " ");
DateTimeFormatter df = DateTimeFormat.forPattern("MMM dd yyyy hh:mma").withZone(DateTimeZone.forID(clientTimeZone));
DateTime temp = df.parseDateTime(value);
System.out.println(temp.getZone().getID());
Timestamp ts1 = new Timestamp(temp.getMillis());
DateTime date = temp.withZoneRetainFields(DateTimeZone.forID("EST"));//withZone(DateTimeZone.forID("EST"));
Timestamp ts = new Timestamp(date.getMillis());
System.out.println(ts1+"="+ts);
When I am running the code I am expecting ts1 to remain same and ts to be up by 1 hr. But iam getting below which I don't understand. I thought EST is one hour ahead of CST and so if it is 11 in CST, it should be 12 in EST. Also there seems to be offset by about eleven and half hours. Any clues on what I am missing.
2014-12-30 11:06:00.0=2014-12-30 10:06:00.0
I think the below code will help you.
String clientTimeZone = "CST6CDT";
String toStimeZone = "EST";
String value = "Dec 29 2014 11:36PM";
TimeZone fromTimeZone = TimeZone.getTimeZone(clientTimeZone);
TimeZone toTimeZone = TimeZone.getTimeZone(toStimeZone);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(fromTimeZone);
SimpleDateFormat sf = new SimpleDateFormat("MMM dd yyyy KK:mma");
Date date = sf.parse(value);
calendar.setTime(date);
System.out.println(date);
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
if (fromTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}
System.out.println(calendar.getTime());
Copied from : http://singztechmusings.wordpress.com/2011/06/23/java-timezone-correctionconversion-with-daylight-savings-time-settings/
The method withZoneRetainFields() preserves the fields in the timezone CST (= UTC-06) hence your local timestamp (as LocalDateTime) but combines it with a different timezone (EST = UTC-05) which is one hour ahead in offset and result in a different instant. You should it interprete it this way: The same local time happens one hour earlier in New York compared to Chicago.
The rule is to subtract positive offsets and to add negative offsets in order to make timestamp representations of instants comparable (normalizing to UTC offset).
Alternatively: Maybe you don't want this but want to preserve the instant instead of the local fields. In this case you have to use the method withZone().
Side notice: Effectively, you compare the instants represented by the variables temp and date and finally use your default timezone to print these instants in the JDBC-escape-format (explanation - you implicitly use Timestamp.toString()). I would rather recommend to use a dedicated instant formatter for this purpose or simpler (to have the offsets in focus):
System.out.println(temp.toInstant() + " = " + date.toInstant());

How can I convert a Timestamp into either Date or DateTime object?

I'm retrieving a timestamp object from a database using ResultSet.getTimestamp(), but I'd like an easy way to get the date in the format of MM/DD/YYYY and the time in a format of HH:MM xx. I was tinkering around, it it looks as though I can do such by making use of the Date and/or DateTime objects within Java. Is that the best way to go, or do I even need to convert the timestamp to accomplish this? Any recommendations would be helpful.
....
while(resultSet.next()) {
Timestamp dtStart = resultSet.getTimestamp("dtStart");
Timestamp dtEnd = resultSet.getTimestamp("dtEnd");
// I would like to then have the date and time
// converted into the formats mentioned...
....
}
....
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(timestamp.getTime());
// S is the millisecond
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss:S");
System.out.println(simpleDateFormat.format(timestamp));
System.out.println(simpleDateFormat.format(date));
}
}
java.sql.Timestamp is a subclass of java.util.Date. So, just upcast it.
Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");
Using SimpleDateFormat and creating Joda DateTime should be straightforward from this point on.
java.time
Modern answer: use java.time, the modern Java date and time API, for your date and time work. Back in 2011 it was right to use the Timestamp class, but since JDBC 4.2 it is no longer advised.
For your work we need a time zone and a couple of formatters. We may as well declare them static:
static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");
Now the code could be for example:
while(resultSet.next()) {
ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
.atZoneSameInstant(zone);
// I would like to then have the date and time
// converted into the formats mentioned...
String dateFormatted = dtStart.format(dateFormatter);
String timeFormatted = dtStart.format(timeFormatter);
System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
}
Example output (using the time your question was asked):
Date: 09/20/2011; time: 18:13 -0400
In your database timestamp with time zone is recommended for timestamps. If this is what you’ve got, retrieve an OffsetDateTime as I am doing in the code. I am also converting the retrieved value to the user’s time zone before formatting date and time separately. As time zone I supplied America/Marigot as an example, please supply your own. You may also leave out the time zone conversion if you don’t want any, of course.
If the datatype in SQL is a mere timestamp without time zone, retrieve a LocalDateTime instead. For example:
ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
.atZone(zone);
No matter the details I trust you to do similarly for dtEnd.
I wasn’t sure what you meant by the xx in HH:MM xx. I just left it in the format pattern string, which yields the UTC offset in hours and minutes without colon.
Link: Oracle tutorial: Date Time explaining how to use java.time.
You can also get DateTime object from timestamp, including your current daylight saving time:
public DateTime getDateTimeFromTimestamp(Long value) {
TimeZone timeZone = TimeZone.getDefault();
long offset = timeZone.getOffset(value);
if (offset < 0) {
value -= offset;
} else {
value += offset;
}
return new DateTime(value);
}
LocalDateTime dtStart = rs.getTimestamp("dtStart").toLocalDateTime();
Converts this Timestamp object to a code LocalDateTime.
The conversion creates a code LocalDateTime that represents the
same year, month, day of month, hours, minutes, seconds and nanos
date-time value as this code Timestamp in the local time zone.
since 1.8

Categories

Resources