I need to create a java.util.Date object with an Australian timezone. this object is required for tag libraries used in downstream components (so I'm stuck with Date).
Here's what I have attempted:
TimeZone timeZone = TimeZone.getTimeZone("Australia/Sydney");
GregorianCalendar defaultDate = new GregorianCalendar(timeZone);
Date date = defaultDate.getTime();
However, "date" always returns the current local time (in my case, ET). What am I doing wrong here? Is it even possible to set a Date object with a different timezone?
Update:
Thanks for the responses! This works if I want to output the formatted date as a string, but not if I want to return a date object. Ex:
Date d = new Date();
DateFormat df = new SimpleDateFormat();
df.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
String formattedDate = df.format(d); // returns Sydney date/time
Date myDate = df.parse(formattedDate); // returns local time(ET)
I think I'm going to end up reworking our date taglib.
Is it even possible to set a Date object with a different timezone?
No, it's not possible. As its javadoc describes, all the java.util.Date contains is just the epoch time which is always the amount of seconds relative to 1 january 1970 UTC/GMT. The Date doesn't contain other information. To format it using a timezone, use SimpleDateFormat#setTimeZone()
getTime is an Unix time in seconds, it doesn't have the timezone, i.e. it's bound to UTC. You need to convert that time to the time zone you want e.b. by using DateFormat.
import java.util.*;
import java.text.*;
public class TzPrb {
public static void main(String[] args) {
Date d = new Date();
System.out.println(d);
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
System.out.println(df.format(d));
df.setTimeZone(TimeZone.getTimeZone("Europe/London"));
System.out.println(df.format(d));
}
}
Related
I am trying to get time (HH:MM) from below code in IST format but it still display UTC date, time.
Please help.
public static void main (String args[]) throws ParseException {
String date = "2021-07-05T14:17:00.000Z";
Calendar now = Calendar.getInstance();
TimeZone timeZone = now.getTimeZone();
String timezoneID = timeZone.getID();
// Convert to System format from UTC
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date actualDate = format1.parse(date);
format1.setTimeZone(TimeZone.getTimeZone(timezoneID));
String date1 = format1.format(actualDate);
String time = date1.substring(11, 16);
String timezoneValue = TimeZone.getTimeZone(timezoneID).getDisplayName(false, TimeZone.SHORT);
String finalTime = time + " " + timezoneValue;
System.out.print(finalTime);
}
java.time
I strongly recommend that you use java.time, the modern Java date and time API, for your date and time work. Then your task becomes pretty simple. Rather than a formatter for your input format I want to define a formatter for your desired time format:
private static final DateTimeFormatter TIME_FORMATTER
= DateTimeFormatter.ofPattern("HH:mm zzz", Locale.ENGLISH);
Now the operation goes in these few lines:
String date = "2021-07-05T14:17:00.000Z";
String finalTime = Instant.parse(date)
.atZone(ZoneId.systemDefault())
.format(TIME_FORMATTER);
System.out.println(finalTime);
Output when I ran in Europe/Dublin time zone:
15:17 IST
Here IST is for Irish Summer Time. IST has several meanings, and I wasn’t sure which one you intended. Also many of the other popular time zone abbreviations are ambiguous. IST may also mean Israel Standard Time, but not here, since Israel uses Israel Daylight Time or IDT at this time of year. One other interpretation is India Standard Time used in India and Sri Lanka, So let’s try running the code in Asia/Kolkata time zone.
19:47 IST
I am exploiting the fact that your string is in ISO 8601 format, the format that the classes of java.time parse and also print as their default, that is, without any specified formatter.
What went wrong in your code?
Your bug is here:
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
You must never hardcode Z as a literal in your format pattern, which is what you are doing when enclosing it in single quotes. The Z is a UTC offset and needs to be parsed as such so that Java knows that your date and time are in UTC (which is what Z means). When you hardcode the Z, SimpleDateFormat understands the date and time to be in the default time zone of the JVM. So when afterward you try to convert into that time zone, the time of day is not changed. You’re converting into the time zone you already had. It’s a no-op.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
Time Zone Abbreviations – Worldwide List
You are parsing the date using your default TimeZone, not UTC.
You never called format1.setTimeZone before parsing. A DateFormat uses the default timezone unless you set it to something else.
Let’s look at each line of your code:
Calendar now = Calendar.getInstance();
TimeZone timeZone = now.getTimeZone();
That is getting the default TimeZone. You don’t need a Calendar object for that; just call TimeZone.getDefault().
String timezoneID = timeZone.getID();
There is no reason to call that. You already have a TimeZone object. Converting it to a string ID and back to a TimeZone is a pointless round-trip operation. So, you should remove all uses of timezoneID.
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
That is the problem. The DateFormat doesn’t treat the 'Z' as anything special; it’s just a literal character which the DateFormat knows not to parse.
You need to actually tell the DateFormat that it’s parsing a UTC time:
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
TimeZone utc = TimeZone.getTimeZone(ZoneOffset.UTC);
format1.setTimeZone(utc);
Date actualDate = format1.parse(date);
Instead of cutting out pieces of a formatted string, make a new DateFormat that does exactly what you want:
DateFormat timeFormat = new SimpleDateFormat("HH:mm z");
String finalTime = timeFormat.format(actualDate);
Since a SimpleDateFormat always uses the default TimeZone when it is created, there is no need to call this format object’s setTimeZone method.
I should mention that the java.time and java.time.format packages are much better for working with dates and times:
String date = "2021-07-05T14:17:00.000Z";
Instant instant = Instant.parse(date);
ZonedDateTime utcDateTime = instant.atZone(ZoneOffset.UTC);
ZonedDateTime istDateTime =
utcDateTime.withZoneSameInstant(ZoneId.systemDefault());
String finalTime = String.format("%tR %<tZ", istDateTime);
// Or:
// String finalTime = istDateTime.toLocalTime() + " "
// + itsDateTime.getZone().getDisplayName(
// TextStyle.SHORT, Locale.getDefault());
format1.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
is what you need since the 3-letter zone names are really deprecated. Plus:
String timezoneValue = format1.getTimeZone().getDisplayName(false, TimeZone.SHORT);
The method Calendar.getInstance() gets a calendar using the default time zone and locale - UTC±00:00.
Use "IST" instead of timeZone.getID().
Exemple:
String date="2021-07-05T14:17:00.000Z";
Calendar now = Calendar.getInstance();
TimeZone timeZone = now.getTimeZone();
String timezoneID = "IST"; // <<<<<
// Convert to System format from UTC
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date actualDate = format1.parse(date);
format1.setTimeZone(TimeZone.getTimeZone(timezoneID));
String date1 = format1.format(actualDate);
String time = date1.substring(11, 16);
String timezoneValue = TimeZone.getTimeZone(timezoneID).getDisplayName(false, TimeZone.SHORT);
String finalTime = time + " " + timezoneValue;
System.out.print(finalTime);
I am having some issues in converting a calendar object to an XMLGregorian calendar in the format of YYYY-MM-DD HH:mm:ss.
My current code is:
Calendar createDate = tRow.getBasic().getDateCreated(0).getSearchValue();
Date cDate = createDate.getTime();
GregorianCalendar c = new GregorianCalendar();
c.setTime(cDate);
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
which returns a date of 2013-01-03T11:50:00.000-05:00.
I would like it to read 2013-01-03 11:50:00.
I have checked a bunch of posts, which use DateFormat to parse a string representation of the date, however my dates are provided to me as a Calendar object, not a string.
I'd appreciate a nudge in the right direction to help me figure this one out.
An XMLGregorianCalendar has a specific W3C string representation that you cannot change.
However, you can format a Date with SimpleDateFormat.
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = dateFormat.format(cDate);
You can get a Date object from a XMLGregorianCalendar object as follows:
xmlCalendar.getGregorianCalendar().getDate()
DateFormat#format takes a Object parameter. From memory, it should accept a Calendar object, if not, it WILL accept a Date object, so you could use Calendar#getTime as a worse case scenario
You can use a instance of SimpleDateFormat to specify a custom formatting. This will ensure that the result is always the same for different systems
Have you seen this tutorial it may help?
http://www.vogella.com/articles/JavaDateTimeAPI/article.html
Speicifcally this code is a good example:
// Format the output with leading zeros for days and month
SimpleDateFormat date_format = new SimpleDateFormat("yyyyMMdd");
System.out.println(date_format.format(cal1.getTime()));
Even with about 15 years in Java one always stumbles over the topic of handling dates and times...
Here's the situation: I get a timestamp from some external system as a String representation. The timestamp's semantic is that it represents an UTC date. This timestamp has to be put in an entity and then into a PostgreSQL database in a TIMESTAMP field. Additionally I need to put the same timestamp as local time (in my case CEST) into the entity and then into the database in a TIMESTAMP WITH TIME ZONE field.
What is the right way to ensure that no matter what the settings of the machine executing the code are, the timestamps get stored correctly in the entity (to make some validations with other UTC timestamps) and in the database (to use them in reports later on)?
Here's the code, which worked fine on my local machine:
SimpleDateFormat sdfUTC = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
sdfUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utcTimestamp = sdfUTC.parse(utcTimestampString);
// getMachinesTimezone is some internal util method giving the TimeZone object of the machines Location
Calendar localTimestamp = new GregorianCalendar(getMachinesTimezone());
localTimestamp.setTimeInMillis(utcTimestamp.getTime());
But when executing the same code on the server, it resulted in different times, so I assume that it's not the correct way to handle it. Any suggestions?
PS: I read about Joda Time when searching in this forum, but in the given project I'm not able to introduce new libraries since I only change an existing module, so I have to live with the standard JDK1.6
If I understand correctly, You need to set the timezone on the same data/calendar object that you are printing. Like this:
private Locale locale = Locale.US;
private static final String[] tzStrings = {
"America/New_York",
"America/Chicago",
"America/Denver",
"America/Los_Angeles",
};
Date now = new Date();
for ( TimeZone z : zones) {
DateFormat df = new SimpleDateFormat("K:mm a,z", locale);
df.setTimeZone(z);
String result = df.format(now);
System.out.println(result);
}
if i set timezone to SimpleDateFormat it is working fine.
here is the sample code...
String date="05/19/2008 04:30 AM (EST)";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm aaa (z)");
TimeZone.setDefault(TimeZone.getTimeZone("PST"));
long millis = sdf.parse(date).getTime();
sdf.setTimeZone(TimeZone.getDefault());
System.out.println(sdf.format(new Date(millis)));
I think you have to set the target time zone in you Calendar object. I think something like:
Calendar localTimestamp = new GregorianCalendar(TimeZone.getTimeZone("GMT+10"));
localTimestamp.setTimeInMillis(utcTimestamp.getTime());
In other case Java takes the default system time zone for the Calendar instance.
You can do it by the below example code.
Date date = new Date();
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("CET"));
Date date1 = dateformat.parse(formatter.format(date));
// Set the formatter to use a different timezone
formatter.setTimeZone(TimeZone.getTimeZone("IST"));
Date date2 = dateformat.parse(formatter.format(date));
// Prints the date in the IST timezone
// System.out.println(formatter.format(date));
I want to remove time from Date object.
DateFormat df;
String date;
df = new SimpleDateFormat("dd/MM/yyyy");
d = eventList.get(0).getStartDate(); // I'm getting the date using this method
date = df.format(d); // Converting date in "dd/MM/yyyy" format
But when I'm converting this date (which is in String format) it is appending time also.
I don't want time at all. What I want is simply "21/03/2012".
You can remove the time part from java.util.Date by setting the hour, minute, second and millisecond values to zero.
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
public static Date removeTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
}
The quick answer is :
No, you are not allowed to do that. Because that is what Date use for.
From javadoc of Date :
The class Date represents a specific instant in time, with millisecond precision.
However, since this class is simply a data object. It dose not care about how we describe it.
When we see a date 2012/01/01 12:05:10.321, we can say it is 2012/01/01, this is what you need.
There are many ways to do this.
Example 1 : by manipulating string
Input string : 2012/01/20 12:05:10.321
Desired output string : 2012/01/20
Since the yyyy/MM/dd are exactly what we need, we can simply manipulate the string to get the result.
String input = "2012/01/20 12:05:10.321";
String output = input.substring(0, 10); // Output : 2012/01/20
Example 2 : by SimpleDateFormat
Input string : 2012/01/20 12:05:10.321
Desired output string : 01/20/2012
In this case we want a different format.
String input = "2012/01/20 12:05:10.321";
DateFormat inputFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = inputFormatter.parse(input);
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
String output = outputFormatter.format(date); // Output : 01/20/2012
For usage of SimpleDateFormat, check SimpleDateFormat JavaDoc.
Apache Commons DateUtils has a "truncate" method that I just used to do this and I think it will meet your needs. It's really easy to use:
DateUtils.truncate(dateYouWantToTruncate, Calendar.DAY_OF_MONTH);
DateUtils also has a host of other cool utilities like "isSameDay()" and the like. Check it out it! It might make things easier for you.
What about this:
Date today = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
today = sdf.parse(sdf.format(today));
What you want is impossible.
A Date object represents an "absolute" moment in time. You cannot "remove the time part" from it. When you print a Date object directly with System.out.println(date), it will always be formatted in a default format that includes the time. There is nothing you can do to change that.
Instead of somehow trying to use class Date for something that it was not designed for, you should look for another solution. For example, use SimpleDateFormat to format the date in whatever format you want.
The Java date and calendar APIs are unfortunately not the most well-designed classes of the standard Java API. There's a library called Joda-Time which has a much better and more powerful API.
Joda-Time has a number of special classes to support dates, times, periods, durations, etc. If you want to work with just a date without a time, then Joda-Time's LocalDate class would be what you'd use.
edit - note that my answer above is now more than 10 years old. If you are using a current version of Java (Java 8 or newer), then prefer to use the new standard date and time classes in package java.time. There are many classes available that represent just a date (day, month, year); a date and time; just a time; etc.
Date dateWithoutTime =
new Date(myDate.getYear(),myDate.getMonth(),myDate.getDate())
This is deprecated, but the fastest way to do it.
May be the below code may help people who are looking for zeroHour of the day :
Date todayDate = new Date();
GregorianCalendar todayDate_G = new GregorianCalendar();
gcd.setTime(currentDate);
int _Day = todayDate_GC.get(GregorianCalendar.DAY_OF_MONTH);
int _Month = todayDate_GC.get(GregorianCalendar.MONTH);
int _Year = todayDate_GC.get(GregorianCalendar.YEAR);
GregorianCalendar newDate = new GregorianCalendar(_Year,_Month,_Day,0,0,0);
zeroHourDate = newDate.getTime();
long zeroHourDateTime = newDate.getTimeInMillis();
Hope this will be helpful.
you could try something like this:
import java.text.*;
import java.util.*;
public class DtTime {
public static void main(String args[]) {
String s;
Format formatter;
Date date = new Date();
formatter = new SimpleDateFormat("dd/MM/yyyy");
s = formatter.format(date);
System.out.println(s);
}
}
This will give you output as21/03/2012
Or you could try this if you want the output as 21 Mar, 2012
import java.text.*;
import java.util.*;
public class DtTime {
public static void main(String args[]) {
Date date=new Date();
String df=DateFormat.getDateInstance().format(date);
System.out.println(df);
}
}
You can write that for example:
private Date TruncarFecha(Date fechaParametro) throws ParseException {
String fecha="";
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
fecha =outputFormatter.format(fechaParametro);
return outputFormatter.parse(fecha);
}
The correct class to use for a date without time of day is LocalDate. LocalDate is a part of java.time, the modern Java date and time API.
So the best thing you can do is if you can modify the getStartDate method you are using to return a LocalDate:
DateTimeFormatter dateFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("en-IE"));
LocalDate d = eventList.get(0).getStartDate(); // We’re now getting a LocalDate using this method
String dateString = d.format(dateFormatter);
System.out.println(dateString);
Example output:
21/03/2012
If you cannot change the getStartDate, you may still be able to add a new method returning the type that we want. However, if you cannot afford to do that just now, convert the old-fashioned Date that you get (I assume java.util.Date):
d = eventList.get(0).getStartDate(); // I'm getting the old-fashioned Date using this method
LocalDate dateWithoutTime = d.toInstant()
.atZone(ZoneId.of("Asia/Kolkata"))
.toLocalDate();
Please insert the time zone that was assumed for the Date. You may use ZoneId.systemDefault() for the JVM’s time zone setting, only this setting can be changed at any time from other parts of your program or other programs running in the same JVM.
The java.util.Date class was what we were all using when this question was asked 6 years ago (no, not all; I was, and we were many). java.time came out a couple of years later and has replaced the old Date, Calendar, SimpleDateFormat and DateFormat. Recognizing that they were poorly designed. Furthermore, a Date despite its name cannot represent a date. It’s a point in time. What the other answers do is they round down the time to the start of the day (“midnight”) in the JVM’s default time zone. It doesn’t remove the time of day, only sets it, typically to 00:00. Change your default time zone — as I said, even another program running in the same JVM may do that at any time without notice — and everything will break (often).
Link: Oracle tutorial: Date Time explaining how to use java.time.
A bit of a fudge but you could use java.sql.Date. This only stored the date part and zero based time (midnight)
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, 2011);
c.set(Calendar.MONTH, 11);
c.set(Calendar.DATE, 5);
java.sql.Date d = new java.sql.Date(c.getTimeInMillis());
System.out.println("date is " + d);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("formatted date is " + df.format(d));
gives
date is 2011-12-05
formatted date is 05/12/2011
Or it might be worth creating your own date object which just contains dates and not times. This could wrap java.util.Date and ignore the time parts of it.
java.util.Date represents a date/time down to milliseconds. You don't have an option but to include a time with it. You could try zeroing out the time, but then timezones and daylight savings will come into play--and that can screw things up down the line (e.g. 21/03/2012 0:00 GMT is 20/03/2012 PDT).
What you might want is a java.sql.Date to represent only the date portion (though internally it still uses ms).
String substring(int startIndex, int endIndex)
In other words you know your string will be 10 characers long so you would do:
FinalDate = date.substring(0,9);
Another way to work out here is to use java.sql.Date as sql Date doesn't have time associated with it, whereas java.util.Date always have a timestamp.
Whats catching point here is java.sql.Date extends java.util.Date, therefore java.util.Date variable can be a reference to java.sql.Date(without time) and to java.util.Date of course(with timestamp).
In addtition to what #jseals has already said. I think the org.apache.commons.lang.time.DateUtils class is probably what you should be looking at.
It's method : truncate(Date date,int field) worked very well for me.
JavaDocs : https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html#truncate(java.util.Date, int)
Since you needed to truncate all the time fields you can use :
DateUtils.truncate(new Date(),Calendar.DAY_OF_MONTH)
If you are using Java 8+, use java.time.LocalDate type instead.
LocalDate now = LocalDate.now();
System.out.println(now.toString());
The output:
2019-05-30
https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
You can also manually change the time part of date and format in "dd/mm/yyyy" pattern according to your requirement.
public static Date getZeroTimeDate(Date changeDate){
Date returnDate=new Date(changeDate.getTime()-(24*60*60*1000));
return returnDate;
}
If the return value is not working then check for the context parameter in web.xml.
eg.
<context-param>
<param-name>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</param-name>
<param-value>true</param-value>
</context-param>
Don't try to make it hard just follow a simple way
date is a string where your date is saved
String s2=date.substring(0,date.length()-11);
now print the value of s2.
it will reduce your string length and you will get only date part.
Can't believe no one offered this shitty answer with all the rest of them. It's been deprecated for decades.
#SuppressWarnings("deprecation")
...
Date hitDate = new Date();
hitDate.setHours(0);
hitDate.setMinutes(0);
hitDate.setSeconds(0);
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