I have a JUnit test that fails because the milliseconds are different. In this case I don't care about the milliseconds. How can I change the precision of the assert to ignore milliseconds (or any precision I would like it set to)?
Example of a failing assert that I would like to pass:
Date dateOne = new Date();
dateOne.setTime(61202516585000L);
Date dateTwo = new Date();
dateTwo.setTime(61202516585123L);
assertEquals(dateOne, dateTwo);
There are libraries that help with this:
Apache commons-lang
If you have Apache commons-lang on your classpath, you can use DateUtils.truncate to truncate the dates to some field.
assertEquals(DateUtils.truncate(date1,Calendar.SECOND),
DateUtils.truncate(date2,Calendar.SECOND));
There is a shorthand for this:
assertTrue(DateUtils.truncatedEquals(date1,date2,Calendar.SECOND));
Note that 12:00:00.001 and 11:59:00.999 would truncate to different values, so this might not be ideal. For that, there is round:
assertEquals(DateUtils.round(date1,Calendar.SECOND),
DateUtils.round(date2,Calendar.SECOND));
AssertJ
Starting with version 3.7.0, AssertJ added an isCloseTo assertions, if you are using the Java 8 Date / Time API.
LocalTime _07_10 = LocalTime.of(7, 10);
LocalTime _07_42 = LocalTime.of(7, 42);
assertThat(_07_10).isCloseTo(_07_42, within(1, ChronoUnit.HOURS));
assertThat(_07_10).isCloseTo(_07_42, within(32, ChronoUnit.MINUTES));
It also works with legacy java Dates as well:
Date d1 = new Date();
Date d2 = new Date();
assertThat(d1).isCloseTo(d2, within(100, ChronoUnit.MILLIS).getValue());
Yet another workaround, I'd do it like this:
assertTrue("Dates aren't close enough to each other!", (date2.getTime() - date1.getTime()) < 1000);
Use a DateFormat object with a format that shows only the parts you want to match and do an assertEquals() on the resulting Strings. You can also easily wrap that in your own assertDatesAlmostEqual() method.
With AssertJ you could provide a custom comparator what is especially handy if you are comparing entire object structures and not single values so that other methods like isEqualToIgnoringMillis or isCloseTo are not practical.
assertThat(thing)
.usingRecursiveComparison()
.withComparatorForType(
(a, b) -> a.truncatedTo(ChronoUnit.MILLIS).compareTo(b.truncatedTo(ChronoUnit.MILLIS)),
OffsetDateTime.class
)
You could do something like this:
assertTrue((date1.getTime()/1000) == (date2.getTime()/1000));
No String comparisons needed.
You can chose which precision level you want when comparing dates, e.g.:
LocalDateTime now = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS);
// e.g. in MySQL db "timestamp" is without fractional seconds precision (just up to seconds precision)
assertEquals(myTimestamp, now);
In JUnit you can program two assert methods, like this:
public class MyTest {
#Test
public void test() {
...
assertEqualDates(expectedDateObject, resultDate);
// somewhat more confortable:
assertEqualDates("01/01/2012", anotherResultDate);
}
private static final String DATE_PATTERN = "dd/MM/yyyy";
private static void assertEqualDates(String expected, Date value) {
DateFormat formatter = new SimpleDateFormat(DATE_PATTERN);
String strValue = formatter.format(value);
assertEquals(expected, strValue);
}
private static void assertEqualDates(Date expected, Date value) {
DateFormat formatter = new SimpleDateFormat(DATE_PATTERN);
String strExpected = formatter.format(expected);
String strValue = formatter.format(value);
assertEquals(strExpected, strValue);
}
}
I don't know if there is support in JUnit, but one way to do it:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Example {
private static SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
private static boolean assertEqualDates(Date date1, Date date2) {
String d1 = formatter.format(date1);
String d2 = formatter.format(date2);
return d1.equals(d2);
}
public static void main(String[] args) {
Date date1 = new Date();
Date date2 = new Date();
if (assertEqualDates(date1,date2)) { System.out.println("true!"); }
}
}
This is actually a harder problem than it appears because of the boundary cases where the variance that you don't care about crosses a threshold for a value you are checking. e.g. the millisecond difference is less than a second but the two timestamps cross the second threshold, or the minute threshold, or the hour threshold. This makes any DateFormat approach inherently error-prone.
Instead, I would suggest comparing the actual millisecond timestamps and provide a variance delta indicating what you consider an acceptable difference between the two date objects. An overly verbose example follows:
public static void assertDateSimilar(Date expected, Date actual, long allowableVariance)
{
long variance = Math.abs(allowableVariance);
long millis = expected.getTime();
long lowerBound = millis - allowableVariance;
long upperBound = millis + allowableVariance;
DateFormat df = DateFormat.getDateTimeInstance();
boolean within = lowerBound <= actual.getTime() && actual.getTime() <= upperBound;
assertTrue(MessageFormat.format("Expected {0} with variance of {1} but received {2}", df.format(expected), allowableVariance, df.format(actual)), within);
}
Using JUnit 4 you could also implement a matcher for testing dates according to your chosen precision. In this example the matcher takes a string format expression as a parameter. The code is not any shorter for this example. However the matcher class may be reused; and if you give it a describing name you can document the intention with the test in an elegant way.
import static org.junit.Assert.assertThat;
// further imports from org.junit. and org.hamcrest.
#Test
public void testAddEventsToBaby() {
Date referenceDate = new Date();
// Do something..
Date testDate = new Date();
//assertThat(referenceDate, equalTo(testDate)); // Test on equal could fail; it is a race condition
assertThat(referenceDate, sameCalendarDay(testDate, "yyyy MM dd"));
}
public static Matcher<Date> sameCalendarDay(final Object testValue, final String dateFormat){
final SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
return new BaseMatcher<Date>() {
protected Object theTestValue = testValue;
public boolean matches(Object theExpected) {
return formatter.format(theExpected).equals(formatter.format(theTestValue));
}
public void describeTo(Description description) {
description.appendText(theTestValue.toString());
}
};
}
use AssertJ assertions for Joda-Time (http://joel-costigliola.github.io/assertj/assertj-joda-time.html)
import static org.assertj.jodatime.api.Assertions.assertThat;
import org.joda.time.DateTime;
assertThat(new DateTime(dateOne.getTime())).isEqualToIgnoringMillis(new DateTime(dateTwo.getTime()));
the test failing message is more readable
java.lang.AssertionError:
Expecting:
<2014-07-28T08:00:00.000+08:00>
to have same year, month, day, hour, minute and second as:
<2014-07-28T08:10:00.000+08:00>
but had not.
If you were using Joda you could use Fest Joda Time.
Just compare the date parts you're interested in comparing:
Date dateOne = new Date();
dateOne.setTime(61202516585000L);
Date dateTwo = new Date();
dateTwo.setTime(61202516585123L);
assertEquals(dateOne.getMonth(), dateTwo.getMonth());
assertEquals(dateOne.getDate(), dateTwo.getDate());
assertEquals(dateOne.getYear(), dateTwo.getYear());
// alternative to testing with deprecated methods in Date class
Calendar calOne = Calendar.getInstance();
Calendar calTwo = Calendar.getInstance();
calOne.setTime(dateOne);
calTwo.setTime(dateTwo);
assertEquals(calOne.get(Calendar.MONTH), calTwo.get(Calendar.MONTH));
assertEquals(calOne.get(Calendar.DATE), calTwo.get(Calendar.DATE));
assertEquals(calOne.get(Calendar.YEAR), calTwo.get(Calendar.YEAR));
JUnit has a built in assertion for comparing doubles, and specifying how close they need to be. In this case, the delta is within how many milliseconds you consider dates equivalent. This solution has no boundary conditions, measures absolute variance, can easily specify precision, and requires no additional libraries or code to be written.
Date dateOne = new Date();
dateOne.setTime(61202516585000L);
Date dateTwo = new Date();
dateTwo.setTime(61202516585123L);
// this line passes correctly
Assert.assertEquals(dateOne.getTime(), dateTwo.getTime(), 500.0);
// this line fails correctly
Assert.assertEquals(dateOne.getTime(), dateTwo.getTime(), 100.0);
Note It must be 100.0 instead of 100 (or a cast to double is needed) to force it to compare them as doubles.
You can use isEqualToIgnoringSeconds method to ignore seconds and compare only by minutes:
Date d1 = new Date();
Thread.sleep(10000);
Date d2 = new Date();
assertThat(d1).isEqualToIgnoringSeconds(d2); // true
Something like this might work:
assertEquals(new SimpleDateFormat("dd MMM yyyy").format(dateOne),
new SimpleDateFormat("dd MMM yyyy").format(dateTwo));
Instead of using new Date directly, you can create a small collaborator, which you can mock out in your test:
public class DateBuilder {
public java.util.Date now() {
return new java.util.Date();
}
}
Create a DateBuilder member and change calls from new Date to dateBuilder.now()
import java.util.Date;
public class Demo {
DateBuilder dateBuilder = new DateBuilder();
public void run() throws InterruptedException {
Date dateOne = dateBuilder.now();
Thread.sleep(10);
Date dateTwo = dateBuilder.now();
System.out.println("Dates are the same: " + dateOne.equals(dateTwo));
}
public static void main(String[] args) throws InterruptedException {
new Demo().run();
}
}
The main method will produce:
Dates are the same: false
In the test you can inject a stub of DateBuilder and let it return any value you like. For example with Mockito or an anonymous class which overrides now():
public class DemoTest {
#org.junit.Test
public void testMockito() throws Exception {
DateBuilder stub = org.mockito.Mockito.mock(DateBuilder.class);
org.mockito.Mockito.when(stub.now()).thenReturn(new java.util.Date(42));
Demo demo = new Demo();
demo.dateBuilder = stub;
demo.run();
}
#org.junit.Test
public void testAnonymousClass() throws Exception {
Demo demo = new Demo();
demo.dateBuilder = new DateBuilder() {
#Override
public Date now() {
return new Date(42);
}
};
demo.run();
}
}
Convert the dates to String using SimpleDateFromat, specify in the constructor the required date/time fields and compare the string values:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String expectedDate = formatter.format(dateOne));
String dateToTest = formatter.format(dateTwo);
assertEquals(expectedDate, dateToTest);
I did a small class that might be useful for some googlers that end up here : https://stackoverflow.com/a/37168645/5930242
Here is a utility function that did the job for me.
private boolean isEqual(Date d1, Date d2){
return d1.toLocalDate().equals(d2.toLocalDate());
}
i cast the objects to java.util.Date and compare
assertEquals((Date)timestamp1,(Date)timestamp2);
Related
I am getting a date value as 1598331600000 from a API call
I am trying to convert this to Readable format using SimpleDateFormat
But i am getting Out of Range Compile Time Error in the Date Constructor
This is my Program
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Calendar cal = Calendar.getInstance();
Date date = new java.sql.Date(1598331600000);
SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMddyyyy");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
}
Could you please let me know how to resolve this error .
1598331600000 without a suffix is treated as an int, and this value is too big for it (int can hold values up to around 2 billion, 2^31 - 1). Use L suffix for long type, which can hold values up to 2^63 - 1: 1598331600000L.
I would recommend to use java-8 date time api, and stop using legacy Calendar, SimpleDateFormat
Instant.ofEpochMilli(1598331600000l)
.atZone(ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern("MMddyyyy")) //08252020
Your value here is treated as integer.
Date date = new java.sql.Date(1598331600000);
The constructor can take Long values. Like this :
long millis=System.currentTimeMillis();
Date date = new java.sql.Date(millis);
Hence it is throwing the error.
Try out this code :
import java.util.*;
import java.text.SimpleDateFormat;
public class Main{
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
/*long millis=System.currentTimeMillis(); <---- This also works
Date date = new java.sql.Date(millis);*/
Date date = new java.sql.Date(1598331600000L); // <---Look the L for Long here
SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMddyyyy");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
}
Output :
08252020
I'm getting my object's createdAt timestamp back from parse.com as 2014-08-01T01:17:56.751Z. I have a class that converts it to relative time.
public static String timeAgo(String time){
PrettyTime mPtime = new PrettyTime();
long timeAgo = timeStringtoMilis(time);
return mPtime.format( new Date( timeAgo ) );
}
public static long timeStringtoMilis(String time) {
long milis = 0;
try {
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sd.parse(time);
milis = date.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return milis;
}
The problem is that this parses the date wrongly. Right now the result says 4 decades ago and this very wrong. What I'm I doing wrong?
Your current date format "yyyy-MM-dd HH:mm:ss" does not work for the given example 2014-08-01T01:17:56.751Z. The format is missing the characters T and Z and the milliseconds.
Change it to:
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
to fix it.
Also check the examples in the JavaDoc of SimpleDateFormat, because it also shows the correct date format for your example: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html.
Expanding #Tom's answer:
The problem
When hardcoding 'Z', you assume that all dates were saved as UTC - which doesn't necessarily have to be the case.
The problem is that SimpleDateFormat does not recognize the literal 'Z'as an alias for UTC's '-0000' offset (For whatever reason, since it claims to be ISO-8601 compliant).
So you can't do
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
since this wrongly assumes all dates will always be written as in UTC, but you can't do
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
either, since this would not be able to parse the date when the literal 'Z' occurs.
Solution 1: Use javax.xml.bind.DatatypeConverter
This datatype converter actually is ISO8601 compliant and can be used as easy as
import javax.xml.bind.DatatypeConverter;
public Long isoToMillis(String dateString){
Calendar calendar = DatatypeConverter.parseDateTime(dateString);
return calendar.getTime().getTime();
}
If you use JAXB anyway, that would be the way to go.
Solution 2: Use conditional formats
final static String ZULUFORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
final static String OFFSETFORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
/* This is a utility method, so you want the calling method
* to be informed that something is wrong with the input format
*/
public static Long isoToMillis(String dateString) throws ParseException{
/* It is the default, so we should use it by default */
String formatString = ZULUFORMAT;
if(! dateString.endsWith("Z") ) {
formatString = OFFSETFORMAT;
}
SimpleDateFormat sd = new SimpleDateFormat(formatString);
return sd.parse(dateString).getTime();
}
If you don't already use JAXB, you might want to put this method into a utility class.
import java.text.DateFormat;
import java.util.Date;
public class DatePlus {
public static void main(String[] args) {
Date now = new Date();
//Date now1 = new Date();
Date now2 = new Date();
DateFormat currentDate = DateFormat.getDateInstance();
int count1=10;
int count2=15;
Date addedDate1 = addDays(now2, count1);
Date addedDate2 = addDays(addedDate1, count2);
System.out.println(currentDate.format(addedDate1));
System.out.println(currentDate.format(addedDate2));
}
public static Date addDays(Date d, int days) {
d.setTime(d.getTime() + days * 1000 * 60 * 60 * 24);
return d;
}
}
both the date addedDate1 and addedDate2 output statements are printing the same date though the expected output is different.
The problem is that you don't return a new Date instance but change the provided one. You always modify and print the same instance.
Change your function to
public static Date addDays(Date d, int days) {
return new Date(d.getTime() + days * 1000 * 60 * 60 * 24);
}
Instead of writing your own method you can use Calender class:
public static void main(String[] args)
{
Date now = new Date();
// Date now2 = new Date();
DateFormat currentDate = DateFormat.getDateInstance();
int count1=10;
int count2=15;
Calendar c=Calendar.getInstance();
c.setTime(now);
c.add(Calendar.DATE, count1);
Date addedDate1 = c.getTime();
c.setTime(addedDate1);
c.add(Calendar.DATE, count2);
Date addedDate2 = c.getTime();
System.out.println(currentDate.format(addedDate1));
System.out.println(currentDate.format(addedDate2));
}
As mentioned already in several answers/comments, doing these calculations manually is risky and error-prone.
Here is a basic example of what you need, using Joda Time library, a very stable and well-design alternative to JDK Date, Calendar. etc...
public static void main(String[] args) {
DateTime now = new DateTime();
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
int count1=10;
int count2=15;
DateTime addedDate1 = now.plusDays(count1);
DateTime addedDate2 = addedDate1.plusDays(count2);
System.out.println(fmt.print(addedDate1));
System.out.println(fmt.print(addedDate2));
}
Also, keep in mind that beside better design and clear documentation, Joda Time also is mostly thread-safe, as it always return immutable objects.
Finally, it's developed to be interoperable with JDK dates and calendars.
As mentionned by dystroy, you are not creating a new instance and this is the problem.
By the way, you could use an external library like Apache Commons Language to do this kind of logic, this is already well tested and you avoid such kind of problems. Commons Language has already an addDays method.
Even better, you could use Joda-Time which also has this kind of methods.
I'm trying to figure out a "simple" way of parsing a String into a Date Object.
The String can be either yyyyMMdd, yyyyMMddHHmm or yyyyMMddHHmmSS.
Currently, I'm looking at the length of the String, and creating a DateParser depending on the length. Is there a more elegant way of doing this?
Or you can pad your string with zeros:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSS") {
#Override
public Date parse(String s) throws ParseException {
return super.parse((s + "000000").substring(0, 14));
}
};
System.out.println(sdf.format(sdf.parse("20110711182405")));
System.out.println(sdf.format(sdf.parse("201107111824")));
System.out.println(sdf.format(sdf.parse("20110711")));
I would do as you are, looking at the length of the string, and creating an appropriate SimpleDateFormat instance.
SimpleDateFormat getFormatFor( String dateString ){
if ( dateString.length() == 8 ) return new SimpleDateFormat("yyyyMMdd");
if ( dateString.length() == 14 ) return new SimpleDateFormat("yyyyMMddHHmmss");
// you got a bad input...
}
NB these are not thread-safe, so you should create a new one each time.
I would use a SimpleDateFormat class, and populate the format pattern based on the length of the string. That'll work fine unless you one day have strings of the same length.
Using the examples from your question:
Formatting 11th July 2011:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date parsedDate = dateFormat.parse("20110711");
Formatting 11th July 2011 1340hrs:
dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
parsedDate = dateFormat.parse("201107111340");
Formatting 11th July 2011 1340hrs 10 seconds:
(NB. small s for seconds, capital S is for Milliseconds!)
dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
parsedDate = dateFormat.parse("20110711134010");
See the hyperlink for the full list of format pattern letters.
You could still used "specialized" parsers (as you suggested) and chain them:
For instance, you can still have a DateHourMinSecParser (for yyyyMMddHHmmSS), a DateHourMinParser (for yyyyMMddHHmm) and a DateParser (for yyyyMMdd) all of them implementing the same interface:
public interface GenericDateParser {
Date parseDate(String input) throws IllegalArgumentException;
}
e.g.
public class DateHourMinSecParser implements GenericDateParser {
...
public Date parseDate(String input) throws IllegalArgumentException {
...
}
}
but each one of these classes would actually take a parameter another GenericDateParser -- the idea being that each parser would try first to parse the date itself, if the parsing (or some internal checks -- e.g. string length) fails it would then pass it to the next parser in chain until either there are no more parsers in the chain (in which case it would throw an exception, or one of the members in the chain would return a value):
public class DateHourMinSecParser implements GenericDateParser {
private GenericDateParser chained;
public DateHourMinSecParser(GenericDateParser chained) {
this.chained = chained;
}
public Date parseDate(String input) throws IllegalArgumentException {
if( !internalChecks() ) { //chain it up
if( chained == null ) throw new IllegalArgumentException( "Don't know how to parse " + input);
}
//internal checks passed so try to parse it and return a Date or throw exception
...
}
}
and you would initialize them:
GenericDateParser p = new DateHourMinSecParser( new DateHourMinParser(new DateParser(null)) );
and then just use the top level one:
Date d = p.parse( '20110126' );
You can use a DateFormatter to parse the Date from the string.
import java.util.*;
import java.text.*;
public class StringToDate
{
public static void main(String[] args)
{
try
{
String str_date="11-June-07";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("yyyy-MM-dd");
date = (Date)formatter.parse(str_date);
}
catch (ParseException e)
{
System.out.println("Exception :"+e);
}
}
}
You can change the pattern however you like to reflect your needs.
I know how to convert local time to UTC time and vice versa.
But I am very much confused about daylight savings time(DST) handling while doing this.
So can anyone answer the below questions:
1. Does java internally handle DST when converting between timezones?
2. What things I need to do while converting between timezones?
3. Any good article which explains about this more clearly?
Thanks in advance.
Are you sure you know how to convert dates to UTC and back? Correctly?
I am afraid, I doubt that.
Yes.
You don't need to convert, you just need to assign correct TimeZone.
What you need an article for? OK, I am working on this, but for now let me put an answer here.
The first thing first. Your program should store Date (or Calendar) in UTC TimeZone internally. Well, in fact in GMT, because there are no leap seconds in Java, but that is another story.
The only place when you should be in need of "converting", is when you are going to display the time to user. That regards to sending email messages as well. In both cases you need to format date to get its textual representation. To that you would use DateFormat and assign correct TimeZone:
// that's for desktop application
// for web application one needs to detect Locale
Locale locale = Locale.getDefault();
// again, this one works for desktop application
// for web application it is more complicated
TimeZone currentTimeZone = TimeZone.getDefault();
// in fact I could skip this line and get just DateTime instance,
// but I wanted to show how to do that correctly for
// any time zone and locale
DateFormat formatter = DateFormat.getDateTimeInstance(
DateFormat.DEFAULT,
DateFormat.DEFAULT,
locale);
formatter.setTimeZone(currentTimeZone);
// Dates "conversion"
Date currentDate = new Date();
long sixMonths = 180L * 24 * 3600 * 1000;
Date inSixMonths = new Date(currentDate.getTime() + sixMonths);
System.out.println(formatter.format(currentDate));
System.out.println(formatter.format(inSixMonths));
// for me it prints
// 2011-05-14 16:11:29
// 2011-11-10 15:11:29
// now for "UTC"
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(formatter.format(currentDate));
System.out.println(formatter.format(inSixMonths));
// 2011-05-14 14:13:50
// 2011-11-10 14:13:50
As you can see, Java cares about handling DST. You can of course handle it manually, just read the TimeZone related JavaDoc.
Here is the best solution that I've found. I'm copying it here, but the solution came from http://biese.wordpress.com/2014/02/28/the-easy-way-to-convert-local-time-to-utc-time/.
package com.test.timezone;
import java.util.TimeZone;
public final class Utility {
public static final TimeZone utcTZ = TimeZone.getTimeZone("UTC");
public static long toLocalTime(long time, TimeZone to) {
return convertTime(time, utcTZ, to);
}
public static long toUTC(long time, TimeZone from) {
return convertTime(time, from, utcTZ);
}
public static long convertTime(long time, TimeZone from, TimeZone to) {
return time + getTimeZoneOffset(time, from, to);
}
private static long getTimeZoneOffset(long time, TimeZone from, TimeZone to) {
int fromOffset = from.getOffset(time);
int toOffset = to.getOffset(time);
int diff = 0;
if (fromOffset >= 0){
if (toOffset > 0){
toOffset = -1*toOffset;
} else {
toOffset = Math.abs(toOffset);
}
diff = (fromOffset+toOffset)*-1;
} else {
if (toOffset <= 0){
toOffset = -1*Math.abs(toOffset);
}
diff = (Math.abs(fromOffset)+toOffset);
}
return diff;
}
}
package com.test.timezone;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class TestTimezone {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss zzzz");
Calendar date1 = new GregorianCalendar(2014,0,15,10,0,0);
System.out.println(sdf.format(date1.getTime())+"\n");
long utcTimeStamp = Utility.toUTC(date1.getTimeInMillis(), date1.getTimeZone());
Calendar utcCal = Calendar.getInstance();
utcCal.setTimeInMillis(utcTimeStamp);
System.out.println("toUTC: "+sdf.format(utcCal.getTime())+"\n");
System.out.println("---------------------------------------");
Calendar date2 = new GregorianCalendar(2014,2,15,10,0,0);
System.out.println(sdf.format(date2.getTime())+"\n");
utcTimeStamp = Utility.toUTC(date2.getTimeInMillis(), date2.getTimeZone());
utcCal.setTimeInMillis(utcTimeStamp);
System.out.println("toUTC: "+sdf.format(utcCal.getTime())+"\n");
System.out.println("---------------------------------------");
Calendar date3 = new GregorianCalendar(2014,11,25,9,0,0);
System.out.println(sdf.format(date3.getTime())+"\n");
long uTime = Utility.toUTC(date3.getTimeInMillis(), date3.getTimeZone());
System.out.println("utcTimeStamp: "+uTime+"\n");
long lTime = Utility.toLocalTime(uTime, TimeZone.getTimeZone("EST"));
Calendar locCal = Calendar.getInstance();
locCal.setTimeInMillis(lTime);
System.out.println("toLocal: "+sdf.format(locCal.getTime())+"\n");
System.out.println("---------------------------------------");
Calendar date4 = new GregorianCalendar(2014,6,4,9,0,0);
System.out.println(sdf.format(date4.getTime())+"\n");
uTime = Utility.toUTC(date4.getTimeInMillis(), date4.getTimeZone());
System.out.println("utcTimeStamp: "+uTime+"\n");
lTime = Utility.toLocalTime(uTime, TimeZone.getTimeZone("EST"));
locCal = Calendar.getInstance();
locCal.setTimeInMillis(lTime);
System.out.println("toLocal: "+sdf.format(locCal.getTime())+"\n");
}
}
The code in TALE's answer can be simplified:
public final class Utility {
public static long toLocalTime(long time, TimeZone to) {
return time + to.getOffset(time);
}
public static long toUTC(long time, TimeZone from) {
return time - from.getOffset(time);
}
}