Get current time and check if time has passed a certain period - java

this code below gets the current time and timezone of the area
Date date = new Date();
DateFormat df = new SimpleDateFormat("HH:mm:ss");
df.setTimeZone(TimeZone.getDefault());
System.out.println("Time: " + df.format(date));
right now its 1:01 pm (at the time of typing)
what i need help doing is implementing a feature in the code that checks if the current time has passed, for example 1:00PM
but I have no idea where to even start, can you help me out?

Use the Java 8+ Time API class LocalTime:
LocalTime refTime = LocalTime.of(13, 0); // 1:00 PM
// Check if now > refTime, in default time zone
LocalTime now = LocalTime.now();
if (now.isAfter(refTime)) {
// passed
}
// Check if now >= refTime, in pacific time zone
LocalTime now = LocalTime.now(ZoneId.of("America/Los_Angeles"))
if (now.compareTo(refTime) >= 0) {
// passed
}

I see it has already answered with Time, but as a teaching point, if you really wanted to use Date, you could have done something like this:
public static void main(String[] args) {
Date date = new Date();
DateFormat df = new SimpleDateFormat("HH:mm:ss");
df.setTimeZone(TimeZone.getDefault());
System.out.println("Time: " + df.format(date));
//If you print the date you'll see how it is formatted
//System.out.println(date.toString());
//So you can just split the string and use the segment you want
String[] fullDate = date.toString().split(" ");
String compareAgainstTime = "01:00PM";
System.out.println(isPastTime(fullDate[3],compareAgainstTime));
}
public static boolean isPastTime(String currentTime, String comparedTime) {
//We need to make the comparison time into the same format as the current time: 24H instead of 12H:
//then we'll just convert the time into only minutes to that we can more easily compare;
int comparedHour = comparedTime[-2].equals("AM") ? String.valueOf(comparedTime[0:2]) : String.valueOf(comparedTime[0:2] + 12 );
int comparedMin = String.valueOf(comparedTime[3:5]);
int comparedT = comparedHour*60 + comparedMin;
//obviously currentTime is alredy the correct format; just need to convert to minutes
int currentHour = String.valueOf(currentTime[0:2]);
int currentMin = String.valueOf(currentTime[3:5]);
int currentT = currentHour*60 + currentMin;
return (currentT > comparedT);
}
It's a bit messier, having to muddy into the Strings and whatnot, but it is possible. You would also have to be careful the zero-pad the comparedTime or just check for that in the function

Related

How to do time running using Java

I have start_time and end_Time, so I tried to print those interval_times (time format 24).
How do I do it?
int start = Integer.parseInt("10:24:49");
int end = Integer.parseInt("11:24:49");
for (int i = start; i < end; i++)
{
System.out.println("result i ="+ i);
}
Since Java 8, the java.time package has been the optimal way to do all date/time related things.
It takes some getting used to, e.g. when it comes to timezones, but it's absolutely worth the effort!
Here's the code for your seconds printer:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public static void main(final String[] args) {
// Just so you know it in the future. Not needed in this example.
final DateTimeFormatter dtfDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.US);
final DateTimeFormatter dtfTime = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.US);
final LocalTime ltStart = LocalTime.of(10, 24, 49);
final LocalTime ltEnd = ltStart.plusHours(1);
// If you want to use String parsing to get your instance:
final LocalTime ltStartViaParsing = LocalTime.from(dtfTime.parse("10:24:49"));
LocalTime i = ltStart;
while (i.isBefore(ltEnd)) {
System.out.println("result i = " + dtfTime.format(i));
i = i.plusSeconds(1);
}
}
Output:
result i = 10:24:49
result i = 10:24:50
result i = 10:24:51
...
result i = 11:24:46
result i = 11:24:47
result i = 11:24:48
It looks like you want to run the loop for particular duration of time.
In case you want to run the loop for fixed duration like for 5 minutes, with a 5 second interval, you can do it like this:
try {
// This loop will run for 5 minutes for every 5 second delay
for(int i=0;i<60;i++) {
System.out.println(new Date());
Thread.sleep(5 * 1000);
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
Before using, see comments below.
If you are intending to print every hour between two given times, then you are totally on the wrong path.
Integer.parseInt
It is intended to get a String number and converts it to Java Integer.
Try to use SimpleDateFormat and Date and Calendar
String startTime = "10:24:49";
String endTime = "11:24:49";
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(startTime));
int start = calendar.get(Calendar.HOUR_OF_DAY);
calendar.setTime(sdf.parse(endTime));
int end = calendar.get(Calendar.HOUR_OF_DAY);
This may help:
DateTime startTime, endTime;
Period p = new Period(startTime, endTime);
int hours = p.getHours();
int minutes = p.getMinutes();
And also you can use Java.util.Timer to schedule a thread to be executed at a certain time in the future.

Checking dates if it is in a range

My Java FX app handles hours worked. I have work start and end time in 2 date fields. I succeeded in calculating the differences between 2 datesTime; but now how could I check if the result is in a night or day range???? The day begin at 6 and ends at 22h. For example someone who worked between 3Am till 11Pm.
Here is below how I did to have the total number of hours worked.
public void CalculNbreJourTravaille() {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyy HH:mm");
try {
Date ddtt = format.parse(ddt.getText());
Date dftt = format.parse(dft.getText());
long diff = dftt.getTime() - ddtt.getTime();
long diffhours = diff / (60*60*1000)%24;
long diffdays = diff/(24*60*60*1000);
long total = diffhours + (diffdays*24);
result.setText(total + " Hours");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
We have workers who can work beyond 10PM, and the pay would not be the same. If they work after 10pm, they will have a special pay. We pay at the end of the work. They could would work only 10 days or more.
You should use the new DateTimeFormatter class to give you a LocalDateTime object, which you can pull the hour from.
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
LocalDateTime localDateTimeFrom = format.parse(dateFrom.getText(), LocalDateTime::from);
LocalDateTime localDateTimeTo = format.parse(dateTo.getText(), LocalDateTime::from);
int hoursFrom = localDateTimeFrom.getHour();
int hoursTo = localDateTimeTo.getHour();
boolean workedNight = hoursFrom < 6 || hoursTo > 22;
Here’s my attempt to cover all of your requirements. I wrote the code before reading that you don’t require that summer time (DST) is taken into account, so I am using ZonedDateTime to get correct hours also across summer time transitions. For the same reason I need to iterate over each day. For each date I calculate the hours worked at night time and the hours worked at day time.
If you want to make sure that summer time is not taken into account, use LocalDateTime instead of ZonedDateTime. In this case there may also be a possible performance gain in calculating the whole work days in one lump rather than one day at a time.
The code below uses 28/03/2018 03:00 and 29/03/2018 23:30 as example start and end time. Expected total hours worked are 44.5 since one day is 24 hours and there are 20.5 hours from 03:00 to 23:30. The expected day time hours are 32 since there are 16 daytime hours each of the two days. This leaves 12.5 hours as night time. And indeed the code prints
Day 32.0 hours; night 12.5 hours
The program follows. Please fill in the correct time zone where I put America/Monterey.
static ZoneId zone = ZoneId.of("America/Monterrey");
static LocalTime dayStart = LocalTime.of(6, 0);
static LocalTime dayEnd = LocalTime.of(22, 0);
static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/uuuu H:mm");
public static void main(String[] args) {
String workStartString = "28/03/2018 03:00";
String workEndString = "29/03/2018 23:30";
calculateWorkingHours(workStartString, workEndString);
}
public static void calculateWorkingHours(String workStartString, String workEndString) {
ZonedDateTime workStart
= LocalDateTime.parse(workStartString, formatter).atZone(zone);
ZonedDateTime workEnd
= LocalDateTime.parse(workEndString, formatter).atZone(zone);
if (workEnd.isBefore(workStart)) {
throw new IllegalArgumentException("Work end must not be before work start");
}
LocalDate workStartDate = workStart.toLocalDate();
LocalDate workEndDate = workEnd.toLocalDate();
Duration workedDaytime = Duration.ZERO;
// first calculate work at nighttime before the start date, that is, work before 06:00
Duration workedNighttime
= calculateNightTime(workStartDate.minusDays(1), workStart, workEnd);
for (LocalDate d = workStartDate; ! d.isAfter(workEndDate); d = d.plusDays(1)) {
workedDaytime = workedDaytime.plus(calculateDayTime(d, workStart, workEnd));
workedNighttime = workedNighttime.plus(calculateNightTime(d, workStart, workEnd));
}
double dayHours = workedDaytime.toMinutes() / (double) TimeUnit.HOURS.toMinutes(1);
double nightHours = workedNighttime.toMinutes() / (double) TimeUnit.HOURS.toMinutes(1);
System.out.println("Day " + dayHours + " hours; night " + nightHours + " hours");
}
/**
* Calculates amount of work in daytime on d,
* that is between 06:00 and 22:00 on d.
* Only time that falls with in workStart to workAnd
* and also falls within 06:00 to 22:00 on d is included.
*
* #param d The date for which to calculate day work
* #param workStart
* #param workEnd
* #return Amount of daytime work on the said day
*/
private static Duration calculateDayTime(LocalDate d, ZonedDateTime workStart, ZonedDateTime workEnd) {
ZonedDateTime dayStartToday = d.atTime(dayStart).atZone(zone);
ZonedDateTime dayEndToday = d.atTime(dayEnd).atZone(zone);
if (workStart.isAfter(dayEndToday) || workEnd.isBefore(dayStartToday)) {
return Duration.ZERO;
}
// restrict calculation to daytime on d
if (workStart.isBefore(dayStartToday)) {
workStart = dayStartToday;
}
if (workEnd.isAfter(dayEndToday)) {
workEnd = dayEndToday;
}
return Duration.between(workStart, workEnd);
}
/**
* Calculates amount of night work in the night after d,
* that is from 22:00 on d until 06:00 the next morning.
*
* #param d The date for which to calculate night work
* #param workStart
* #param workEnd
* #return Amount of nighttime work in said night
*/
private static Duration calculateNightTime(LocalDate d, ZonedDateTime workStart, ZonedDateTime workEnd) {
assert ! workEnd.isBefore(workStart);
ZonedDateTime nightStart = d.atTime(dayEnd).atZone(zone);
ZonedDateTime nightEnd = d.plusDays(1).atTime(dayStart).atZone(zone);
if (workEnd.isBefore(nightStart) || workStart.isAfter(nightEnd)) {
return Duration.ZERO;
}
// restrict calculation to the night after d
if (workStart.isBefore(nightStart)) {
workStart = nightStart;
}
if (workEnd.isAfter(nightEnd)) {
workEnd = nightEnd;
}
return Duration.between(workStart, workEnd);
}
You can check the LocalTime part of a LocalDateTime to have a simple check using isAfter and isBefore.
I will use those values for this example.
LocalDateTime start = LocalDateTime.of(2018, Month.APRIL, 30, 23, 0);
LocalDateTime end = LocalDateTime.of(2018, Month.MAY, 1, 5, 0);
Then define the limit for the night.
LocalTime startNight = LocalTime.of(22, 0);
LocalTime endNight = LocalTime.of(6, 0);
And simply use get the LocalTime of both date and check if they are in the range. You can get the value using toLocalTime.
if(start.toLocalTime().isAfter(startNight) &&
end.toLocalTime().isBefore(endNight)){
System.out.println("NIGHT TIME");
} else {
System.out.println("DAY TIME");
}
NIGHT TIME
The output is valid since we start at 23:00 and end at 05:00.
Using this allow a simpler solution if you need to define a time like LocalTime.of(5,45) for 5:45
This is an example, this might need some adaptation if it is allowed to start part 22 but keep working after 6. This is just an example on how to use those methods.
This is easier, if you use the java.time API. You simply need to check, if the dates differ or if the starting time not in the range from 6:00 to 22:00:
private static final LocalTime START_TIME = LocalTime.of(6, 0); // 06:00
private static final LocalTime END_TIME = LocalTime.of(22, 0); // 22:00
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
// parse from input strings
LocalDateTime start = LocalDateTime.parse(startText, FORMATTER);
LocalDateTime end = LocalDateTime.parse(endText, FORMATTER);
boolean nightTime =
!start.toLocalDate().equals(end.toLocalDate())
|| start.toLocalTime().isBefore(START_TIME)
|| end.toLocalTime().isAfter(END_TIME);
// todo: change output to gui
System.out.println("night time: " + nightTime);
System.out.println("duration : " + Duration.between(start, end).toHours());
Define two formatters. One Fromatter to get date with time from edittext. And other On to get 12AM of that day. Now we need Date Objects corresponding to 6AM and 11PM of the same day. We can get those by adding that much milliseconds to the 12AM Object. These added dates can be used for comparison.
SimpleDateFormat df_zero_hours = new SimpleDateFormat("dd/MM/yyy");
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date ddtt = format.parse(ddt.getText()); //Work Start Time
Date dftt = format.parse(dft.getText()); //Work End Time
Date dateStart = df_zero_hours.parse(ddt.getText()); //12AM of the day job started
Date dayStart = new Date();
dayStart.setTime(dateStart.getTime()+6*60*60*1000); // Get 6AM of that day
Date dayEnd = new Date();
dayEnd.setTime(dateStart.getTime()+22*60*60*1000); //Get 10PM of that day
// Now check the worked hours. in Whatever way you need
boolean isBefore6AM = (dayStart.getTime()-ddtt.getTime())>0;
boolean isAfter10PM = (dftt.getTime()-dayEnd.getTime())>0;

How to add time period in Android program?

I'm writing an aplication for Android and I need to add "sleep time" period in my program. I don't know how to implement this. I have a sevice in my program and service must be switched off during certain periods of time (eg 22:00 - 7:00). Advise whether there is any ready solution for this kind of problem? I'm interested in is how to set this time period, thank you. Sorry for my English.
You may try to add this to get the current date and time:
String str = DateFormat.getDateTimeInstance().format(new Date());
After that you can check that the time is within the range you want.
public static final String myformat = "HH:mm";
private Date date;
private Date time1;
private Date time2;
private String range1 = "10:00";
private String range2 = "07:00";
SimpleDateFormat str = new SimpleDateFormat(myformat, Locale.US);
private void checkRange(){
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
date = parseDate(hour + ":" + minute);
time1= parseDate(range1);
tim2= parseDate(range2);
if ( time1.before( date ) && time2.after(date)) {
//code
}
}
Eventually written following function using JodaTime:
SharedPreferences sp = context.getSharedPreferences(Constants.SP_SETTINGS,Context.MODE_PRIVATE);
String start = sp.getString(Constants.PARAM_SLEEP_MODE_START,null);
String end = sp.getString(Constants.PARAM_SLEEP_MODE_END,null);
if (start==null || end ==null) return null;
DateTime now = new DateTime(new Date());
Days days = Days.daysBetween(new DateTime(new Date(0)).toLocalDate(),now.toLocalDate());
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
DateTime begin = formatter.parseDateTime(start).plusDays(days.getDays());
DateTime finish = formatter.parseDateTime(end).plusDays(days.getDays());
if (begin.isAfter(finish)) {
if (now.isBefore(finish)) begin = begin.minusDays(1);
else finish = finish.plusDays(1);
} else {
if (now.isAfter(finish)) {
begin = begin.plusDays(1);
finish = finish.plusDays(1);
}
}
Interval interval = new Interval(begin,finish);
return interval.contains(now);
It is very well defines what I want. Thank you all =)

convert a string of time to 24 hour format

I have a string holding a start time and an end time in this format 8:30AM - 9:30PM I want to be able to strip out the AM - and the PM and convert all the times to 24 hour format so 9:30PM would really be 21:30 and also have both the times stored in 2 different variables, I know how to strip the string into substrings but Im not sure about the conversion, this is what I have so far. the time variable starts out holding 8:30AM - 9:30PM.
String time = strLine.substring(85, 110).trim();
//time is "8:30AM - 9:30PM"
String startTime;
startTime = time.substring(0, 7).trim();
//startTime is "8:30AM"
String endTime;
endTime = time.substring(9).trim();
//endTime "9:30AM"
Working code (considering that you managed to split the Strings):
public class App {
public static void main(String[] args) {
try {
System.out.println(convertTo24HoursFormat("12:00AM")); // 00:00
System.out.println(convertTo24HoursFormat("12:00PM")); // 12:00
System.out.println(convertTo24HoursFormat("11:59PM")); // 23:59
System.out.println(convertTo24HoursFormat("9:30PM")); // 21:30
} catch (ParseException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Replace with KK:mma if you want 0-11 interval
private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mma");
// Replace with kk:mm if you want 1-24 interval
private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm");
public static String convertTo24HoursFormat(String twelveHourTime)
throws ParseException {
return TWENTY_FOUR_TF.format(
TWELVE_TF.parse(twelveHourTime));
}
}
Now that I think about it, SimpleDateFormat, H h K k can be confusing.
Cheers.
You need to use: SimpleDateFormat
And can refer this tutorial: Formatting hour using SimpleDateFormat
Example:
//create Date object
Date date = new Date();
//formatting hour in h (1-12 in AM/PM) format like 1, 2..12.
String strDateFormat = "h";
SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
System.out.println("hour in h format : " + sdf.format(date));
I wouldn't reinvent the wheel (unless you are doing this as a school project or some such).
Just get a date object out of your time stamp and then you can generate whatever format you want with this: SimpleDateFormat
[edited to address your specific request]
if you absolutely need to work from your own unique strings, then you'll do something like this (I don't know exactly what your strings look like... you're using offsets like 85, which means nothing out of context).
I didn't check this for bugs, but this is approximately what you want...
myStr = timestampString.toLowerCase(); //something like 8:30am
boolean add12 = (myStr.indexOf("pm") != -1)?true:false;
//convert hour to int
int hour = Integer.parseInt(myStr.split(":")[0]);
int minutes = Integer.parseInt( myStr.split(":")[1].replaceAll("\\D+","").replaceAll("^0+","") ); //get the letters out of the minute part and get a number out of that, also, strip out leading zeros
int militaryTime = hour + (add12)? 12:0;
if(!add12 && militaryTime == 12)
militaryTime = 0; //account for 12am
//dont' forget to add the leading zeros back in as you assemble your string
With Joda Time, the code looks like:
DateTimeFormatter formatter12 = DateTimeFormat.forPattern("K:mma");
DateTime begin = formatter12.parseDateTime(beginTime);
DateTime end = formatter12.parseDateTime(endTime);
DateTimeFormatter formatter24 = DateTimeFormat.forPattern("k:mma");
String begin24 = formatter24.print(begin);
String end24 = formatter24.print(end);
I should like to contribute the modern answer
DateTimeFormatter twelveHourFormatter = DateTimeFormatter.ofPattern("h:mma", Locale.ENGLISH);
String time = "8:30AM - 9:30PM";
String[] times = time.split(" - ");
LocalTime start = LocalTime.parse(times[0], twelveHourFormatter);
System.out.println(start.toString());
LocalTime end = LocalTime.parse(times[1], twelveHourFormatter);
System.out.println(end.toString());
This prints:
08:30
21:30
I am using java.time, the modern Java date and time API. The SimpleDateFormat class used in many of the other answers is long outdated and was always troublesome. java.time is so much nicer to work with than the date-time classes from the 1990’s. A LocalTime is a time of day without a date (and without time zone), so suits your need much better than an old-fashioned Date.
Link: Oracle tutorial: Date Time explaining how to use java.time.
24 hour time adds 12 to any time greater than 12pm so that 1pm is 13 and so on until 24 or 12am. Here is the sudo code:
if(hour <= 12)
{
hour = hour + 12;
}
All the below lines will works when
String str="07:05:45PM";
and when you call timeConversion(str) and want to convert to 24 hours format..
public class TimeConversion {
private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mm:ssa");
private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm:ss");
static String timeConversion(String s) {
String str = null;
try {
str= TWENTY_FOUR_TF.format(
TWELVE_TF.parse(s));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
public static void main(String[] args) throws ParseException {
String str="07:05:45PM";
System.out.println(timeConversion(str));
}
}

Converting local time to UTC time or vice versa considering daylight saving time

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);
}
}

Categories