I tried many ways to display the difference between two times, but I am unable to find a solution:
long strt = System.currentTimeMillis();//1462968291733
Thread.sleep(5000);
long end = System.currentTimeMillis();//1462968296733
long diff = end - strt;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(diff);
TimeZone timeZone = TimeZone.getTimeZone("IST");
calendar.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
System.out.println(calendar.getTime());//05:30:05
It is printing wrong output:
Thu Jan 01 05:30:05 IST 1970
The output should be
Thu Jan 01 00:00:05 IST 1970
You are getting confuse with the time zone. Try the following:
long strt = System.currentTimeMillis();// 1462968291733
Thread.sleep(5000);
long end = System.currentTimeMillis();// 1462968296733
long diff = end - strt;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(diff);
TimeZone cutsomTimeZone = TimeZone.getTimeZone("IST");
DateFormat formatter = new SimpleDateFormat
("EEE MMM dd HH:mm:ss zzz yyyy");
formatter.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
System.out.println(formatter.format(calendar.getTime()));//
formatter.setTimeZone(cutsomTimeZone);
System.out.println(formatter.format(calendar.getTime()));
First, as the javadoc says, System.currentMillis() return the number of milliseconds since 1 January 1970 in UTC which is obviously different from IST.
Second, the Date object return by calendar.getTime() does not bear a timezone. The output you get with System.out.println(calendar.getTime()) use the default TimeZone of your system which seems to be IST.
Third, please don't use the Date api, it is really bad. When possible, prefer the java.time one.
This is because the default print out uses the default locale, which is +5:30 in your case.
You'll need to format the output in the time zone you want, e.g. by using SimpleDateFormat:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(calendar.getTime()));
The answer by dejvuth and the answer by orris are both correct.
Avoid the old date-time classes. They have been supplanted in Java 8 and later by the java.time framework. For Java 6 & 7, much of the functionality has been back-ported by the ThreeTen-Backport project, and further adapted to Android by the ThreeTenABP project.
No need for time zones at all to capture elapsed time.
An Instant represents a moment on the timeline in UTC with a resolution of up to nanoseconds. In Java 8 the current moment is captured up to a resolution of only milliseconds, but a new implementation of Clock in Java 9 will capture up to nanoseconds depending on your computer’s clock hardware capability.
Instant start = Instant.now();
…
Instant stop = Instant.now();
A Duration captures a span of time as a total number of whole seconds and a fraction of a second as nanoseconds. This value is not attached to the timeline.
Duration duration = Duration.between( start , stop );
The java.time classes use the ISO 8601 standard when generating a textual representation of a date-time value. For a duration of two and a half seconds, you will get a value like PT2.5S where the P marks the beginning (for Period), and the T separates any years-month-days from hours-minutes-seconds. This format prevents the ambiguity of the clock-format where 00:00:02.5 looks like a time-of-day of two minutes past midnight. But if you so desire you can interrogate the Duration for the numbers.
String output = duration.toString();
Related
This question already has answers here:
Convert timestamp in milliseconds to string formatted time in Java
(10 answers)
Closed 5 years ago.
I Have the following code in my application
System.out.println(rec.getDateTrami().getTime());
I need to convert the following format (I suppose that they are seconds)
43782000
29382000
29382000
To a format YYYY-MM-DD HH24:MI:SS, anyone can help to me?
You can make use of the SimpleDateFormat
Example:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = new Date();
date.setTime(rec.getDateTrami().getTime());
System.out.println(format.format(date));
Documentation:
SimpleDateFormat,
DateFormat
Use java.time
Best if you can change getDateTrami() to return an OffsetDateTime or ZonedDateTime from java.time. java.time is the modern Java date and time API. It is also known as JSR-310. The code is the same no matter which of the two mentioned types is returned:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
System.out.println(rec.getDateTrami().format(formatter));
This prints a date and time like
2017-12-14 16:52:20
java.time is generally so much nicer to work with than the outmoded Date class and its friends.
If you cannot change the return type
I assume getDateTrami() returns a java.util.Date. Since the Date class is long outmoded, the first thing to do is to convert it to java.time.Instant. From there you perform your further operations:
Date oldfashionedDateObject = rec.getDateTrami();
ZonedDateTime dateTime = oldfashionedDateObject.toInstant()
.atZone(ZoneId.of("Atlantic/Cape_Verde"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
System.out.println(dateTime.format(formatter));
The result is similar to the above, of course. I on purpose made explicit in which time zone I want to interpret the point in time. Please substitute your own if it doesn’t happen to be Atlantic/Cape_Verde.
Formatting seconds since the epoch
int seconds = 29_382_000;
ZonedDateTime dateTime = Instant.ofEpochSecond(seconds)
.atZone(ZoneId.of("Atlantic/Cape_Verde"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
System.out.println(dateTime.format(formatter));
This snippet prints
1970-12-06 23:40:00
A date in December 1970. If this is incorrect, it is because 29 382 000 didn’t denote seconds since the epoch of January 1, 1970 at midnight in UTC, also known as the Unix epoch. This is by far the most common time to measure seconds from. If your seconds are measured from some other fixed point in time, I cannot guess which, and you have got a job to do to find out. Again decide which time zone you want to specify.
You could use SimpledateFormat.
new SimpleDateFormat("YYYY-MM-DD HH24:MI:SS").format(date)
How can I convert time from unix timestamp to week day? For example, I want to convert 1493193408 to Wednesday.
I tryed code above, but It always shows Sunday..
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408);
String weekday = sdf.format(dateFormat );
Using java.time
The other Answers use the troublesome old date-time classes, now legacy, supplanted by the java.time classes.
Time zone is crucial in determining a date, and therefore getting a day-of-week.
Get an Instant from your count of while seconds since the epoch of 1970 in UTC. Apply a time zone to get a ZonedDateTime. From there extract a DayOfWeek enumerate object. Ask that object to automatically localize to generate a string of its name.
Instant.ofEpochSecond( 1_493_193_408L )
.atZone( ZoneId.of( "America/Montreal" ))
.getDayOfWeek()
.getDisplayName( TextStyle.FULL , Locale.US )
For Android, see the ThreeTenABP project for a back-port of most of the java.time functionality.
You need to multiply it by 1000 since Java and Unix time are not the same.
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408L * 1000);
String weekday = sdf.format(dateFormat );
You can use a calendar instance because it provides you methods for getting that information:
Date date = new Date(1493193408000L);
Calendar c = Calendar.getInstance();
c.setTime(date);
System.out.println(c.get(Calendar.DAY_OF_WEEK));
System.out.println(c.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US));
The Date constructor has the following description:
Allocates a Date object and initializes it to represent the specified
number of milliseconds since the standard base time known as "the
epoch", namely January 1, 1970, 00:00:00 GMT.
Your timestamp is in seconds, if you multiply by 1000 (to get milliseconds) you get the expected answer:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408000L);
System.out.println(dateFormat);
String weekday = sdf.format(dateFormat);
System.out.println(weekday);
Which prints
Wed Apr 26 09:56:48 CEST 2017
Wednesday
dateFormatStart != dateFormat
You could also check using:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new Date(System.currentTimeMillis());
String weekday = sdf.format(dateFormat);
Here is right code for you:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408 * 1000);
String weekday = sdf.format(dateFormat );
There is documentation for Java date
You can do the same with the new JDK 8 date time classes. Local date and time is calculated using the seconds from Unix Epoch and then it can be formatted with a specific pattern. The conversion to date time takes into account the Zone as well, I have used the default Zone, but it can be modified to use a specific zone.
ZonedDateTime ldt = ZonedDateTime.ofInstant(Instant.ofEpochSecond(1493193408), ZoneId.systemDefault());
System.out.println(ldt.format(DateTimeFormatter.ofPattern("EEEE")));
It’s been said already: your problem is your are feeding number seconds since the Unix epoch into a Date when it expects the number of milliseconds (then one would have expected multiplying by 1000 to be simple, but a couple of the other answers got that part wrong).
If you are going to work with dates, times or weekdays in your app, I agree with the answers that recommend that you consider the newer classes in java.time. They are much nicer to work with. Your code will more directly express your intent.
But if you only need the weekday, a dependency on a third party library may be overkill. I still recommend keeping a distance to the oldfashioned classes SimpleDateFormat, Date and Calendar, though. Is there a third option? There certainly is! A simple oneliner, even:
String weekday = String.format(Locale.ENGLISH, "%tA", 1493193408 * 1000L);
This yields Wednesday as desired. You must still be aware that the result depends on your computer’s time zone setting, though.
I am trying to convert a string such as
String dateString = "Mon Mar 30 13:51:35 UTC 2015";
in a Date Object.
I tried this:
DateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZ yyyy", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("Date Object:"+sdf.parse(dateString));
But the output of the date object is
Mon Mar 30 15:51:35 CEST 2015
as you can see:
1) it forwards the string's time ahead to two hours
2) it changes UTC --> CEST
I tried many solutions, but nothing worked. What is the correct way to do this?
EDIT: my objective here is to have a Date object from that original String. That Date Object should have the same parameters as the date string. In this case, the original hours of day (13) is turned to 15, but the desired is for it to stay at 13. I need this because in my program I will need to compare two different date objects.
EDIT: JAVA 8 SOLUTION
Searching the more recent Java 8, I found a better and more elegant solution. Here is the code
String pattern = "EEE MMM dd HH:mm:ss SSS zzz yyyy";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.UK).withZone(ZoneId.of("UTC"));
final ZonedDateTime parsed = ZonedDateTime.parse(dateString, formatter);
Furthermore, to compare it with, for example, the current time:
ZonedDateTime now = ZonedDateTime.now();
int compared = parsed.compareTo(now);
System.out.println("NOW:"+now.toLocalDateTime()+" PARSED:"+parsed.toLocalDateTime()+" COMPARED:"+compared);
You are doing it correctly. The date is being parsed correctly. You are just printing the date into your local computer timezone. When you do toString() to a date, prints the date in your local machine timezone.
Mon Mar 30 15:51:35 CEST 2015 == Mon Mar 30 13:51:35 UTC 2015
CEST is UTC +2
A java.util.Date does not have a time zone, practically speaking. There is a time zone inside but it cannot be set nor gotten. One of many poor design decisions made in these old date-time classes.
The Date::toString method applies your JVM’s current default time zone when generating the output string. Done with good intentions, but not helpful as it creates the illusion your Date object is in that zone when in fact it is not.
java.time
You are using a troublesome old legacy class, now supplanted by the java.time framework built into Java 8 and later.
Convert from a Date to an Instant, a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = myJavaUtilDate.toInstant();
Call toString. The java.time classes use standard ISO 8601 formats when parsing/generating strings.
String output = instant.toString();
To create strings, convert from Instant to OffsetDateTime using the constant ZoneOffset.UTC. Then work with the java.time.format classes to generate the string.
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , ZoneOffset.UTC );
Search Stack Overflow for more info and examples. These issues have addressed hundreds of times already.
Instead of UTC, use GMT when getting the timezone.
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Source
You already have the Date object. If you want to print it in format you want, you can use DateFormat to format the Date object as well:
Date date = sdf.parse(dateString);
System.out.println("Date Object:"+sdf.format(date));
// Use the date object ...
What I am trying to do is store a date, represented by a long of milliseconds, that is the next midnight from the current time. So, posting this at 10:11 PM, I would want a date representing 12:00 AM tomorrow morning. For this task, I wrote this line of code (knowing that there are 86400000 milliseconds in one day):
long time = System.currentTimeMillis() + (86400000 - (System.currentTimeMillis() % 86400000));
The line is designed to calculate the extra milliseconds from the last midnight, substract that from one whole day to find the time until the next midnight, then add that to the current time so that the new value is the value of the next midnight. For whatever reason though, the date object I am using to debug spits out "Wed Apr 20 20:00:00 EDT 2016" when calling the #toString() method. The current time is said to be "Tue Apr 19 22:08:34 EDT 2016" at the same time as the other date is being calculated.
This means that the long of milliseconds is actually representing 8:00 PM the next day, while I want it to represent 12:00 AM. Can anyone help me spot the flaw in my logic?
I most likely am missing something obvious, so bear with me.
NOTE: I also tried calculating the time like this:
long time = System.currentTimeMillis() - (System.currentTimeMillis() % 86400000) + 86400000;
But this resulted in the same Date object.
You are forgetting to adjust for your timezone. Here is a simple way to achieve this.
TimeZone tz = TimeZone.getDefault();
long time = System.currentTimeMillis() + (86400000 - (System.currentTimeMillis() % 86400000));
time -= tz.getOffset(time);
System.out.println(new Date(time));
java.time
You are using flawed troublesome date-time classes that have long been supplanted, first by the Joda-Time library and now it's successor, the java.time framework built into Java 8 and later. Much of java.time has been back-ported to Java 6 & 7 and then adapted to Android by the ThreeTenABP project.
An Instant is a moment on the timeline in UTC, with a resolution in nanoseconds.
Instant instant = Instant.now();
Apply a time zone to get a ZonedDateTime. Time zone is crucial to determining a date. It may already be “tomorrow” to the east of you or “yesterday” to the west.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( zoneId );
To get the first moment of the day, do not assume that time is 00:00:00.0. Anomalies such as Daylight Saving Time may result in a different time. Let java.time determine that time-of-day. To do that we must go through the LocalDate class.
LocalDate today = zdt.toLocalDate();
Days are not always 24 hours long, which is an incorrect assumption in you question and code. Again, let java.time determine the following day with a call to plusDays.
LocalDate tomorrow = LocalDate.plusDays( 1 );
ZonedDateTime zdtTomorrowStart = tomorrow.atStartOfDay( zoneId );
I suggest you avoid tracking date-time values as a count from epoch. That is prone to error, and is terribly difficult to debug. And you will be losing data as you go from nanosecond resolution to milliseconds. But if you insist.
long millis = zdtTomorrowStart.toInstant().toEpochMilli();
Direct time calculation can be tricky, there are quite a few corner cases. I think the simplest solution to avoid it is :
// now, with current timezone and locale
Calendar calendar = new GregorianCalendar();
// tomorrow
calendar.add(Calendar.DAY_OF_MONTH, 1);
// midnight
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
// get the resulting date
Date date = calendar.getTime();
I have a Timestamp value that comes from my application. The user can be in any given local TimeZone.
Since this date is used for a WebService that assumes the time given is always in GMT, I have a need to convert the user's parameter from say (EST) to (GMT). Here's the kicker: The user is oblivious to his TZ. He enters the creation date that he wants to send to the WS, so what I need is:
User enters: 5/1/2008 6:12 PM (EST)
The parameter to the WS needs to be: 5/1/2008 6:12 PM (GMT)
I know TimeStamps are always supposed to be in GMT by default, but when sending the parameter, even though I created my Calendar from the TS (which is supposed to be in GMT), the hours are always off unless the user is in GMT. What am I missing?
Timestamp issuedDate = (Timestamp) getACPValue(inputs_, "issuedDate");
Calendar issueDate = convertTimestampToJavaCalendar(issuedDate);
...
private static java.util.Calendar convertTimestampToJavaCalendar(Timestamp ts_) {
java.util.Calendar cal = java.util.Calendar.getInstance(
GMT_TIMEZONE, EN_US_LOCALE);
cal.setTimeInMillis(ts_.getTime());
return cal;
}
With the previous Code, this is what I get as a result (Short Format for easy reading):
[May 1, 2008 11:12 PM]
public static Calendar convertToGmt(Calendar cal) {
Date date = cal.getTime();
TimeZone tz = cal.getTimeZone();
log.debug("input calendar has date [" + date + "]");
//Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
long msFromEpochGmt = date.getTime();
//gives you the current offset in ms from GMT at the current date
int offsetFromUTC = tz.getOffset(msFromEpochGmt);
log.debug("offset is " + offsetFromUTC);
//create a new calendar in GMT timezone, set to this date and add the offset
Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
gmtCal.setTime(date);
gmtCal.add(Calendar.MILLISECOND, offsetFromUTC);
log.debug("Created GMT cal with date [" + gmtCal.getTime() + "]");
return gmtCal;
}
Here's the output if I pass the current time ("12:09:05 EDT" from Calendar.getInstance()) in:
DEBUG - input calendar has date [Thu Oct 23 12:09:05 EDT 2008]
DEBUG - offset is -14400000
DEBUG - Created GMT cal with date [Thu Oct 23 08:09:05 EDT 2008]
12:09:05 GMT is 8:09:05 EDT.
The confusing part here is that Calendar.getTime() returns you a Date in your current timezone, and also that there is no method to modify the timezone of a calendar and have the underlying date rolled also. Depending on what type of parameter your web service takes, your may just want to have the WS deal in terms of milliseconds from epoch.
Thank you all for responding. After a further investigation I got to the right answer. As mentioned by Skip Head, the TimeStamped I was getting from my application was being adjusted to the user's TimeZone. So if the User entered 6:12 PM (EST) I would get 2:12 PM (GMT). What I needed was a way to undo the conversion so that the time entered by the user is the time I sent to the WebServer request. Here's how I accomplished this:
// Get TimeZone of user
TimeZone currentTimeZone = sc_.getTimeZone();
Calendar currentDt = new GregorianCalendar(currentTimeZone, EN_US_LOCALE);
// Get the Offset from GMT taking DST into account
int gmtOffset = currentTimeZone.getOffset(
currentDt.get(Calendar.ERA),
currentDt.get(Calendar.YEAR),
currentDt.get(Calendar.MONTH),
currentDt.get(Calendar.DAY_OF_MONTH),
currentDt.get(Calendar.DAY_OF_WEEK),
currentDt.get(Calendar.MILLISECOND));
// convert to hours
gmtOffset = gmtOffset / (60*60*1000);
System.out.println("Current User's TimeZone: " + currentTimeZone.getID());
System.out.println("Current Offset from GMT (in hrs):" + gmtOffset);
// Get TS from User Input
Timestamp issuedDate = (Timestamp) getACPValue(inputs_, "issuedDate");
System.out.println("TS from ACP: " + issuedDate);
// Set TS into Calendar
Calendar issueDate = convertTimestampToJavaCalendar(issuedDate);
// Adjust for GMT (note the offset negation)
issueDate.add(Calendar.HOUR_OF_DAY, -gmtOffset);
System.out.println("Calendar Date converted from TS using GMT and US_EN Locale: "
+ DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
.format(issueDate.getTime()));
The code's output is: (User entered 5/1/2008 6:12PM (EST)
Current User's TimeZone: EST
Current Offset from GMT (in hrs):-4 (Normally -5, except is DST adjusted)
TS from ACP: 2008-05-01 14:12:00.0
Calendar Date converted from TS using GMT and US_EN Locale: 5/1/08 6:12 PM (GMT)
You say that the date is used in connection with web services, so I assume that is serialized into a string at some point.
If this is the case, you should take a look at the setTimeZone method of the DateFormat class. This dictates which time zone that will be used when printing the time stamp.
A simple example:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Calendar cal = Calendar.getInstance();
String timestamp = formatter.format(cal.getTime());
You can solve it with Joda Time:
Date utcDate = new Date(timezoneFrom.convertLocalToUTC(date.getTime(), false));
Date localDate = new Date(timezoneTo.convertUTCToLocal(utcDate.getTime()));
Java 8:
LocalDateTime localDateTime = LocalDateTime.parse("2007-12-03T10:15:30");
ZonedDateTime fromDateTime = localDateTime.atZone(
ZoneId.of("America/Toronto"));
ZonedDateTime toDateTime = fromDateTime.withZoneSameInstant(
ZoneId.of("Canada/Newfoundland"));
It looks like your TimeStamp is being set to the timezone of the originating system.
This is deprecated, but it should work:
cal.setTimeInMillis(ts_.getTime() - ts_.getTimezoneOffset());
The non-deprecated way is to use
Calendar.get(Calendar.ZONE_OFFSET) + Calendar.get(Calendar.DST_OFFSET)) / (60 * 1000)
but that would need to be done on the client side, since that system knows what timezone it is in.
Method for converting from one timeZone to other(probably it works :) ).
/**
* Adapt calendar to client time zone.
* #param calendar - adapting calendar
* #param timeZone - client time zone
* #return adapt calendar to client time zone
*/
public static Calendar convertCalendar(final Calendar calendar, final TimeZone timeZone) {
Calendar ret = new GregorianCalendar(timeZone);
ret.setTimeInMillis(calendar.getTimeInMillis() +
timeZone.getOffset(calendar.getTimeInMillis()) -
TimeZone.getDefault().getOffset(calendar.getTimeInMillis()));
ret.getTime();
return ret;
}
Date and Timestamp objects are timezone-oblivious: they represent a certain number of seconds since the epoch, without committing to a particular interpretation of that instant as hours and days.
Timezones enter the picture only in GregorianCalendar (not directly needed for this task) and SimpleDateFormat, which need a timezone offset to convert between separate fields and Date (or long) values.
The OP's problem is right at the beginning of his processing: the user inputs hours, which are ambiguous, and they are interpreted in the local, non-GMT timezone; at this point the value is "6:12 EST", which can be easily printed as "11.12 GMT" or any other timezone but is never going to change to "6.12 GMT".
There is no way to make the SimpleDateFormat that parses "06:12" as "HH:MM" (defaulting to the local time zone) default to UTC instead; SimpleDateFormat is a bit too smart for its own good.
However, you can convince any SimpleDateFormat instance to use the right time zone if you put it explicitly in the input: just append a fixed string to the received (and adequately validated) "06:12" to parse "06:12 GMT" as "HH:MM z".
There is no need of explicit setting of GregorianCalendar fields or of retrieving and using timezone and daylight saving time offsets.
The real problem is segregating inputs that default to the local timezone, inputs that default to UTC, and inputs that really require an explicit timezone indication.
Something that has worked for me in the past was to determine the offset (in milliseconds) between the user's timezone and GMT. Once you have the offset, you can simply add/subtract (depending on which way the conversion is going) to get the appropriate time in either timezone. I would usually accomplish this by setting the milliseconds field of a Calendar object, but I'm sure you could easily apply it to a timestamp object. Here's the code I use to get the offset
int offset = TimeZone.getTimeZone(timezoneId).getRawOffset();
timezoneId is the id of the user's timezone (such as EST).
java.time
The modern approach uses the java.time classes that supplanted the troublesome legacy date-time classes bundled with the earliest versions of Java.
The java.sql.Timestamp class is one of those legacy classes. No longer needed. Instead use Instant or other java.time classes directly with your database using JDBC 4.2 and later.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = myResultSet.getObject( … , Instant.class ) ;
If you must interoperate with an existing Timestamp, convert immediately into java.time via the new conversion methods added to the old classes.
Instant instant = myTimestamp.toInstant() ;
To adjust into another time zone, specify the time zone as a ZoneId object. Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter pseudo-zones such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
Apply to the Instant to produce a ZonedDateTime object.
ZonedDateTime zdt = instant.atZone( z ) ;
To generate a string for display to the user, search Stack Overflow for DateTimeFormatter to find many discussions and examples.
Your Question is really about going the other direction, from user data-entry to the date-time objects. Generally best to break your data-entry into two parts, a date and a time-of-day.
LocalDate ld = LocalDate.parse( dateInput , DateTimeFormatter.ofPattern( "M/d/uuuu" , Locale.US ) ) ;
LocalTime lt = LocalTime.parse( timeInput , DateTimeFormatter.ofPattern( "H:m a" , Locale.US ) ) ;
Your Question is not clear. Do you want to interpret the date and the time entered by the user to be in UTC? Or in another time zone?
If you meant UTC, create a OffsetDateTime with an offset using the constant for UTC, ZoneOffset.UTC.
OffsetDateTime odt = OffsetDateTime.of( ld , lt , ZoneOffset.UTC ) ;
If you meant another time zone, combine along with a time zone object, a ZoneId. But which time zone? You might detect a default time zone. Or, if critical, you must confirm with the user to be certain of their intention.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
To get a simpler object that is always in UTC by definition, extract an Instant.
Instant instant = odt.toInstant() ;
…or…
Instant instant = zdt.toInstant() ;
Send to your database.
myPreparedStatement.setObject( … , instant ) ;
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.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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.