how to get a formatted date as milliseconds? - java

I have a formatted date from sqllite database, to use this in a graph view I need to format it in a long number.
The format is:
2012-07-11 10:55:21
how can I convert it to milliseconds?

You can convert the string into a Date object using this code:-
Date d = DateFormat.parse(String s)
And then convert it into milliseconds by using the inbuilt method
long millisec = d.getTime();

Use date.getTime()
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd, HH:mm:ss");
formatter.setLenient(false);
String oldTime = "2012-07-11 10:55:21";
Date oldDate = formatter.parse(oldTime);
long oldMillis = oldDate.getTime();

try this:
import java.util.*;
public class ConvertDateIntoMilliSecondsExample{
public static void main(String args[]){
//create a Date object
Date date = new Date();
System.out.println("Date is : " + date);
//use getTime() method to retrieve milliseconds
System.out.println("Milliseconds since January 1, 1970, 00:00:00 GMT : "
+ date.getTime());
}
}

java.time
Solution using java.time, the modern date-time API*:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(toMillis("2012-07-11 10:55:21"));
}
public static long toMillis(String strDateTime) {
// Replace the parameter, ZoneId.systemDefault() which returns JVM's default
// timezone, as applicable e.g. to ZoneId.of("America/New_York")
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u-M-d H:m:s", Locale.ENGLISH)
.withZone(ZoneId.systemDefault());
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
Instant instant = zdt.toInstant();
return instant.toEpochMilli();
}
}
Output:
1342000521000
Learn more about the the modern date-time API* from Trail: Date Time.
*For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Related

Java Convert String and Long to DateTime

I would like to generate a DateTime variable from two different variables (get the date from myLongDateAndTime and time from myStringTime, how can I do that?
String myStringTime="12:30:10"; // Come from DB
long myLongDateAndTime= 1628197200000 // Come from another DB stores date and times in timestamp format of Thu Aug 05 2021 17:00:00 GMT-0400
DateTime myDateTime=??? // should get Thu Aug 05 2021 12:30:10
java.time
Quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
import java.time.Instant;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
String myStringTime = "12:30:10";
long myLongDateAndTime = 1628197200000L;
LocalTime time = LocalTime.parse(myStringTime);
System.out.println(time);
Instant instant = Instant.ofEpochMilli(myLongDateAndTime);
System.out.println(instant);
OffsetDateTime odt = instant.atOffset(ZoneOffset.of("-04:00"));
System.out.println(odt);
odt = odt.with(time);
System.out.println(odt);
}
}
Output:
12:30:10
2021-08-05T21:00:00Z
2021-08-05T17:00-04:00
2021-08-05T12:30:10-04:00
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
Just for the sake of completeness
Just for the sake of completeness, given below is the solution using the Joda Date-Time API:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;
public class Main {
public static void main(String[] args) {
String myStringTime = "12:30:10";
long myLongDateAndTime = 1628197200000L;
LocalTime time = LocalTime.parse(myStringTime);
System.out.println(time);
DateTime dateTime = new DateTime(Long.valueOf(myLongDateAndTime), DateTimeZone.forOffsetHours(-4));
System.out.println(dateTime);
dateTime = dateTime.withTime(time);
System.out.println(dateTime);
}
}
Output:
12:30:10.000
2021-08-05T17:00:00.000-04:00
2021-08-05T12:30:10.000-04:00
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
You are combining two dates, so what you need to do is:
create a joda DateTime from the long
format that DateTime to a string with only the date part
combine with date string and time string in a single string
parse the new string
and here is how you can do that:
public DateTime combineDates(long myLongDateAndTime, String myStringTime) {
// 1 - create DateTime from the long
DateTime dateFromLong = new DateTime(myLongDateAndTime);
// 2 - Format dateFromLong as date string
DateTimeFormatter dtfDate = DateTimeFormat.forPattern("dd/MM/yyyy");
String dateString = dtfDate.print(dateFromLong);
// 3 - Concatenate date part and time part in a new string
String completeDate = dateString + " " + myStringTime;
// 4 - Parse the new string in to a DateTime
DateTimeFormatter dtfDateTime =
DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
return dtfDateTime.parseDateTime(completeDate);
}
This is only a possible solution. There are many other ways to do the same, for example without using a string concatenation, but only dates operations, but this way is quite clear and readable, so I don't investigate additional possible solutions.
One possible solution:
public class TestSample {
public static void main(String[] args) {
String myStringTime="12:30:10";
Long myLongDateAndTime= 1628197200000L;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.ENGLISH);
LocalTime time = LocalTime.parse(myStringTime, formatter);
LocalDate date = Instant.ofEpochMilli(myLongDateAndTime).atZone(ZoneId.of("UTC")).toLocalDate();
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
LocalDateTime dtTime = LocalDateTime.parse(date.toString()+" "+time.toString(), formatter1);
System.out.println(dtTime.toString());
}
}

How to set String date to calendar in Java

I have a calendar in Android and when I'm passing custom date as a default date to my calendar after setting the time to calendar. when I'm clicking the calendar to get default date I'm getting one previous date. for ex - 02/02/2021.
What's wrong I'm doing? how to get date that i passed on calendar?
String dbDate = "03/02/2021"; // (dd/MM/yyyy)
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date dateObj = null;
try{
dateObj = simpleDateFormat.parse(dbDate);
}catch (Exception e){
e.printStackTrace();
}
calendar.clear();
calendar.setTime(dateObj);
long year2021 = calendar.getTimeInMillis();
CalendarConstraints.Builder constraintsBuilder = new CalendarConstraints.Builder();
constraintsBuilder.setStart(year2021);
builder = MaterialDatePicker.Builder.datePicker();
builder.setTitleText("SELECT A DATE");
builder.setSelection(year2021);
builder.setCalendarConstraints(constraintsBuilder.build());
materialDatePicker = builder.build();
The legacy date-time API (java.util date-time types and their formatting type, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
Solution using the modern API:
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String dbDate = "03/02/2021";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d/M/u", Locale.ENGLISH);
LocalDate date = LocalDate.parse(dbDate, dtf);
ZonedDateTime zdtUtc = date.atStartOfDay(ZoneId.of("Etc/UTC"));
Instant instant = zdtUtc.toInstant();
long millis = instant.toEpochMilli();
System.out.println(instant);
System.out.println(millis);
}
}
Output:
2021-02-03T00:00:00Z
1612310400000
Now, you can set millis to builder as follows:
builder.setSelection(millis);
For any reason, if you need to convert this object of Instant to an object of java.util.Date, you can do so as follows:
Date utilDate = Date.from(instant);
Learn more about the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

How can I retrieve datetiime from mongodb? By comparing the data with jDateChosser Java

private void showdataTable_btnActionPerformed(java.awt.event.ActionEvent evt) {
try {
DateFormat df = new SimpleDateFormat("YYYY-mm-dd'T'HH:MM:ss'Z'"); //set date format
String set = df.format(dateChoos1.getDate()); //add value to set
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("datetimes", set); //where date via set(date)
DBCursor cursor = table.find(whereQuery);
while (cursor.hasNext()) {
DBObject obj = cursor.next();
String ip_address = (String) obj.get("ip_address");
String mac_address = (String) obj.get("mac_address");
Date datetimes = (Date) obj.get("datetimes");
String url = (String) obj.get("url");
model.insertRow(model.getRowCount(), new Object[]{datetimes, ip_address, mac_address, url});
}
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
Your format, YYYY-mm-dd'T'HH:MM:ss'Z' is not correct. Let's discuss everything which is wrong with this format.
You have used Y instead of y: The symbol Y is used for Week year while y is used for Year. Check Difference between year-of-era and week-based-year? to learn more about it.
You have used mm for month: The correct symbol for the month is M.
You have used MM for minutes: The correct symbol for the minute is m.
You have enclosed Z within single quotes: The symbol, Z is used for Time zone whereas 'Z' is nothing but a character literal. Probably you want to format the timezone offset of +00:00 as Z and for this, you should in fact use X.
So, the correct format is as follows:
yyyy-MM-dd'T'HH:mm:ssX
A demo with the suggested format:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX", Locale.ENGLISH);
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
System.out.println(sdf.format(date));
}
}
Output:
2021-01-14T08:13:01Z
Note that the date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Use Date#toInstant to convert a java.util.Date object (the legacy type) to java.time.Instant (the modern type). Instant represents an instantaneous point on the time-line and should be just enough for most of your JSON operations. The Instant#toString returns the date-time string with UTC timezone offset which is compliant with ISO-8601 standards.
Demo:
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
Instant instant = date.toInstant();
// Print the value of instant#toString
System.out.println(instant);
OffsetDateTime odt = instant.atOffset(ZoneOffset.UTC);
System.out.println(odt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssX", Locale.ENGLISH);
System.out.println(dtf.format(odt));
}
}
Output:
2021-01-14T08:28:35.659Z
2021-01-14T08:28:35.659Z
2021-01-14T08:28:35Z

Adding/Subtracting 5 seconds from Java Date - Showing deprected warning

I want to add 5 seconds to current time
Date date = new Date();
date.setSeconds(date.getSeconds()+ 5);
System.out.println("old Value is: "+date);
System.out.println("New Value is: "+ date);
It generates the correct output exactly what I needed as:
Old Value is: Thu Apr 17 14:10:33 PKT 2014
New Value is: Thu Apr 17 14:10:38 PKT 2014
but it gives me a warning error message as
Multiple markers at this line
- The method getSeconds() from the type Date is deprecated
- The method setSeconds(int) from the type Date is
deprecated
What this means. Is it safe to ignore this warning? if not then how to handle it?
you can use date.setTime(date.getTime() + 5000)
You can try this. Calendar is the best solution you are looking at.
Date date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.parse("2014-04-17 14:53:25");
Calendar calendar=Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.SECOND,(calendar.get(Calendar.SECOND)-5));
System.out.println(calendar.getTime());
Out put:
Thu Apr 17 14:53:20 IST 2014
deprecated means that this method should't be used anymore because it can be removed from the Java language in favor of some other method (it probably won't be removed but it's not the preferable way of doing things anymore). Documentation suggests you to use Calendar.get(Calendar.SECOND) which is what you should use in your code.
Note that from Java 8 you can use LocalDateTime#getSecond method again.
Java 8 has completly different time-api and makes handling dates a lot easier. Here's an article
With Java Versions 5-7 (everything below should not be used IMHO) you should use Calendar (as Petr suggested)
If you are allowed to use third-party APIs, you should definitly take a look at JodaTime
showing deprecated warning that means
there is some better way available in java to do so.
java.time
The future visitors of this page are recommended to use java.time API. The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Just local time:
import java.time.LocalTime;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
// ZoneId.systemDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to ZoneId.of("Europe/London")
LocalTime localTimeNow = LocalTime.now(ZoneId.systemDefault());
System.out.println(localTimeNow);
// After 5 seconds
LocalTime localTimeAfter5Sec = localTimeNow.plusSeconds(5);
System.out.println(localTimeAfter5Sec);
}
}
Local date & time:
import java.time.LocalDateTime;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
// ZoneId.systemDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to ZoneId.of("Europe/London")
LocalDateTime ldtNow = LocalDateTime.now(ZoneId.systemDefault());
System.out.println(ldtNow);
// After 5 seconds
LocalDateTime ldtAfter5Sec = ldtNow.plusSeconds(5);
System.out.println(ldtAfter5Sec);
}
}
Date & time with timezone:
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
// ZoneId.systemDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to ZoneId.of("Europe/London")
ZonedDateTime zdtNow = ZonedDateTime.now(ZoneId.systemDefault());
System.out.println(zdtNow);
// After 5 seconds
ZonedDateTime zdtAfter5Sec = zdtNow.plusSeconds(5);
System.out.println(zdtAfter5Sec);
}
}
An instantaneous point on the time-line:
java.time.Instant models a single instantaneous point on the time-line and is independent of timezone. It's most commonly used functions, toEpochMilli and ofEpochMilli are used to convert an instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z, and milliseconds from the epoch of 1970-01-01T00:00:00Z to an instant respectively. Note that Z stands for Zulu and represents UTC+00:00.
import java.time.Instant;
public class Main {
public static void main(String[] args) {
// This moment
Instant now = Instant.now();
System.out.println(now);
// Moment after 5 sec
Instant momentAfter5Sec = now.plusSeconds(5);
System.out.println(momentAfter5Sec);
}
}
Learn more about the modern date-time API from Trail: Date Time.
Joda-time
An excerpt from the Home Page of Joda-Time
Joda-Time is the de facto standard date and time library for Java
prior to Java SE 8. Users are now asked to migrate to java.time
(JSR-310).
Just local time:
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;
public class Main {
public static void main(String[] args) {
// DateTimeZone.getDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to DateTimeZone.forID("Europe/London")
LocalTime localTimeNow = LocalTime.now(DateTimeZone.getDefault());
System.out.println(localTimeNow);
// After 5 seconds
LocalTime localTimeAfter5Sec = localTimeNow.plusSeconds(5);
System.out.println(localTimeAfter5Sec);
}
}
Local date & time:
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
// DateTimeZone.getDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to DateTimeZone.forID("Europe/London")
LocalDateTime ldtNow = LocalDateTime.now(DateTimeZone.getDefault());
System.out.println(ldtNow);
// After 5 seconds
LocalDateTime ldtAfter5Sec = ldtNow.plusSeconds(5);
System.out.println(ldtAfter5Sec);
}
}
Date & time with timezone:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public class Main {
public static void main(String[] args) {
// DateTimeZone.getDefault() returns the time-zone of JVM. Change it as per your
// requirement e.g. to DateTimeZone.forID("Europe/London")
DateTime dtNow = new DateTime(DateTimeZone.getDefault());
System.out.println(dtNow);
// After 5 seconds
DateTime dtAfter5Sec = dtNow.plusSeconds(5);
System.out.println(dtAfter5Sec);
}
}
An instantaneous point on the time-line:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public class Main {
public static void main(String[] args) {
DateTime now = new DateTime(DateTimeZone.UTC);
System.out.println(now);
// After 5 seconds
DateTime after5Sec = now.plusSeconds(5);
System.out.println(after5Sec);
}
}
Legacy API:
The java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the milliseconds from the Epoch of January 1, 1970. When you print an object of java.util.Date, its toString method returns the date-time calculated from this milliseconds value. Since java.util.Date does not have timezone information, it applies the timezone of your JVM and displays the same. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFomrat and obtain the formatted string from it.
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());
calendar.add(Calendar.SECOND, 5);// -5 if you want to subtract
System.out.println(calendar.getTime());
}
}
java.time.Instant as the bridge between the legacy and the modern API:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
Instant instant = date.toInstant();
// Now you can convert instant to other types of java.time e.g.
ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Dubai"));
System.out.println(zdt);
}
}
For whatsoever purpose, if you want to convert instant to an object of java.util.Date:
Date dateTime = Date.from(instant);
Easiest solution:
if it is the current date use:
Long seconds= 10; //update in seconds
//seconds*1000 to convert second to millisecond
Date dateAfterUpdation = new Date(System.currentTimeMillis() - (seconds*1000) );
For a specific Date:
Long seconds= 10; //update in seconds
//seconds*1000 to convert second to millisecond
Date dateAfterUpdation = new Date(oldDate.getTime() - (seconds*1000) );
Similarly, you can add or subtract any amount of time by this trick.
FYI, here is some example code using Joda-Time 2.3. The bundled java.util.Date and .Calendar classes are notoriously troublesome, and should be avoided.
Unlike a java.util.Date, a Joda-Time DateTime object has an assigned time zone.
When specifying time zones, use a proper time zone name. Avoid the three or four letter codes as they are neither standardized nor unique.
java.util.Date date = new java.util.Date(); // Has no time zone. Misnamed, as it contains both a date and a time portions.
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Karachi" );
DateTime dateTime = new DateTime( date, timeZone );
DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC );
DateTime fiveSecondsAgo = dateTime.minusSeconds( 5 );
java.util.Date date2 = fiveSecondsAgo.toDate();
Dump to console…
System.out.println( "date: " + date );
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "fiveSecondsAgo: " + fiveSecondsAgo );
System.out.println( "date2: " + date2 );
When run…
date: Thu Apr 17 14:44:01 PDT 2014
dateTime: 2014-04-18T02:44:01.773+05:00
dateTimeUtc: 2014-04-17T21:44:01.773Z
fiveSecondsAgo: 2014-04-18T02:43:56.773+05:00
date2: Thu Apr 17 14:43:56 PDT 2014
An easy way is to use apache DateUtils.
import org.apache.commons.lang.time.DateUtils;
DateUtils.addSeconds(now, 5); // Add 5 seconds.
DateUtils.addSeconds(now, -5); // Subtracting 5 seconds
You can also add/subtract minutes, hours, and so on...

Timezone conversion for a specific datetime in java

I will be giving input date time for a timezone and the timezone for the input date time and we want the relevant DateTime in the expected timezone.
And here is my method.
convertToTimezone("03/08/2010 20:19:00 PM","Asia/Shanghai","US/Central");
The above time is the time in Asia/Shanghai. We would like to know what is the corresponding time in US/Central.
It's working fine but I am getting a 1-hour difference from the actual time.
Can I know where I am going wrong?
Here is the code:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class DateUtil {
private static String format_date = "MM/dd/yyyy HH:mm:ss a";
public static void main(String a[]) {
try {
String sourceTimezone = "Asia/Shanghai";
String destTimezone = "US/Central";
String outputExpectedTimezone = convertToTimezone("03/08/2010 20:19:00 PM", sourceTimezone, destTimezone);
System.out.println("outputExpectedTimezone :" + outputExpectedTimezone);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static String convertToTimezone(String inputDate, String inputDateTimezone, String destinationDateTimezone)
throws Exception {
String outputDate = null;
SimpleDateFormat format = new SimpleDateFormat(format_date);
format.setTimeZone(TimeZone.getTimeZone(inputDateTimezone));
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(inputDateTimezone));
calendar.setTime(format.parse(inputDate));
calendar.add(Calendar.MILLISECOND, -(calendar.getTimeZone().getRawOffset()));
calendar.add(Calendar.MILLISECOND, -calendar.getTimeZone().getDSTSavings());
calendar.add(Calendar.MILLISECOND, TimeZone.getTimeZone(destinationDateTimezone).getRawOffset());
outputDate = format.format(calendar.getTime());
return outputDate;
}
}
You shouldn't be adding anything to the calendar - that represents a specific instant in time. In fact, you don't need a calendar at all.
Instead, have two different formats, one for each time zone:
public static String convertToTimezone(String inputDate,
String inputDateTimezone,
String destinationDateTimezone)
throws Exception
{
SimpleDateFormat parser = new SimpleDateFormat(format_date);
parser.setTimeZone(TimeZone.getTimeZone(inputDateTimezone));
Date date = parser.parse(inputDate);
SimpleDateFormat formatter = new SimpleDateFormat(format_date);
formatter.setTimeZone(TimeZone.getTimeZone(outputDateTimezone));
return formatter.format(date);
}
As an aside, I'd thoroughly recommend using Joda Time instead of the built-in date/time API.
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
Since your input Date-Time does not have timezone information, parse it into a LocalDateTime
Attach the timezone of the input Date-Time with it to get a ZonedDateTime
Use the ZonedDateTime#withZoneSameInstant to convert this ZonedDateTime to the target ZonedDateTime
Return the formatted target ZonedDateTime.
Demo:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Tests
System.out.println(convertToTimezone("03/08/2010 20:19:00 PM", "Asia/Shanghai", "US/Central"));
System.out.println(convertToTimezone("03/08/2010 20:19:00 PM", "Asia/Shanghai", "America/Mexico_City"));
}
static String convertToTimezone(String inputDate, String inputDateTimezone, String destinationDateTimezone) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss a", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(inputDate, dtf);
ZonedDateTime zdtInput = ldt.atZone(ZoneId.of(inputDateTimezone));
ZonedDateTime zdtDestination = zdtInput.withZoneSameInstant(ZoneId.of(destinationDateTimezone));
return zdtDestination.format(dtf);
}
}
Output:
03/08/2010 06:19:00 AM
03/08/2010 06:19:00 AM
ONLINE DEMO
Note: Avoid using the deprecated ID, US/Central. Use the standard ID, America/Mexico_City where Mexico City is the largest city in this timezone.
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Categories