How to get the current UTC time in seconds - java

I have an application, which needs to compare the time in seconds.
I want to know how to get the current UTC time in seconds.
Can some one post an example of it how can we do this in Java?

You can use this to get timezone passing in timezone you want time back in
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Then you can call whatever you want on the calendar object
System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.HOUR));
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
System.out.println(cal.get(Calendar.MINUTE));
Below example to compare two calendars in seconds
Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// Set the dates for calendars
cal1.set(2011, 1, 1);
cal2.set(2011, 2, 2);
// Get the represented date in milliseconds as a long
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();
// Calculate difference in milliseconds
long diff = milis2 - milis1;
// Calculate difference in seconds
long diffSecs = diff / 1000;
System.out.println("In seconds: " + diffSecs + " seconds");

System.currentTimeMillis()

public static long getUtcTime(long time) {
System.out.println("Time="+time);
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date dbefore=new Date(time);
System.out.println("Date before conversion="+format.format(dbefore));
Calendar c = Calendar.getInstance();
c.setTimeInMillis(time);
TimeZone timezone = c.getTimeZone();
int offset = timezone.getRawOffset();
if(timezone.inDaylightTime(new Date())){
offset = offset + timezone.getDSTSavings();
}
int offsetHrs = offset / 1000 / 60 / 60;
int offsetMins = offset / 1000 / 60 % 60;
System.out.println("offset: " + offsetHrs);
System.out.println("offset: " + offsetMins);
c.add(Calendar.HOUR_OF_DAY, (-offsetHrs));
c.add(Calendar.MINUTE, (-offsetMins));
System.out.println("Date after conversion: "+format.format(c.getTime()));
System.out.println("Time converted="+c.getTime().getTime());
return c.getTime().getTime();
}

Joda makes everything simple
import org.joda.time.ReadableInstant;
import org.joda.time.DateTime;
import static org.joda.time.DateTimeZone.UTC;
import static org.joda.time.Seconds.secondsBetween;
...
ReadableInstant start = new DateTime("2011-01-01", UTC);
ReadableInstant end = new DateTime("2011-02-02", UTC);
int secondsDifference = secondsBetween(start, end).getSeconds();

Get current UTC time in seconds (since 1.5) :
TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())
according to Javadoc:
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/System.html#currentTimeMillis
Returns:
the difference, measured in milliseconds, between the current time and
midnight, January 1, 1970 UTC.

To store the date as an integer instead of long, you can divide by 1000 and optionally subtract by another date, such as Jan. 1 2019:
private int getUTC()
{
Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal1.set(2019, 1, 1);
long millis1 = cal1.getTimeInMillis();
//Current date in milliseconds
long millis2 = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
// Calculate difference in seconds
long diff = millis2 - millis1;
return (int)(diff / 1000);
}

This works:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
GregorianCalendar gregorianCalendar = new GregorianCalendar
(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
calendar.get(Calendar.SECOND)
);
return gregorianCalendar.getTime();

Related

I want to get time difference between two time in milisecond

I want to get time difference between two times in milliseconds.
Note
If the difference is above half a second they return 1000 millisecond, so how to get
proper millisecond like if difference of half second to get 500 millisecond
Difference between two times is half second then my code returns
1000 milliseconds that means 1 Second but actually its 0.5 Second so how get 500
milliseconds if difference is half second
Date Date1 = sdf.parse(lastTime);
Date Date2 = sdf.parse(sdf.format(Calendar.getInstance().getTime()));
long millie = Date2.getTime() - Date1.getTime();
SimpleDateFormat does not include milliseconds by default. So
sdf.format(Calendar.getInstance().getTime());
does not output the milliseconds and everything is rounded to seconds.
Define a custom date format including milliseconds like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ\"");
If you use java8 then try with this:
LocalDateTime startTime = LocalDateTime.of(2018,07,31,12,1);
long diff = ChronoUnit.MILLIS.between(startTime,LocalDateTime.now());
you can find difference between two date in millisecond,second,minutes and hours by calling following method, you can change method by your requirements.
public void printDifference(Date startDate) {
Date endDate=new Date();
long different = endDate.getTime() - startDate.getTime(); //Different in miliseconds
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
int months=0,year=0;
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
}
try my below code:
Date date = null;
String value="3 Feb 2018 13:01:41 GMT";
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
date = formatter.parse(value);
} catch (Exception e) {
e.printStackTrace();
}
// Prints the date in the CET timezone
System.out.println("ConvertTime from serverformat before settimezone ::" + formatter.format(date));
// Set the formatter to use a different timezone
formatter.setTimeZone(TimeZone.getDefault());
// Prints the date in the IST timezone
System.out.println("ConvertTime from serverformat after settimezone ::" + formatter.format(date));
DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
Date dateobj = new Date();
System.out.println("Current date and time before settimezone:: " + df.format(dateobj));
df.setTimeZone(TimeZone.getDefault());
System.out.println("current format after settimezone ::" + df.format(dateobj));
int difference = 0;
int diff_Minutes=0;
int diff_Seconds=0;
System.out.println("Default values::" + difference+" "+diff_Minutes+" "+diff_Seconds);
difference = (int) (dateobj.getTime() - date.getTime());
diff_Minutes = difference / (60 * 1000) % 60;
diff_Seconds = difference / 1000 % 60;
here i am converting current time from server time . here u have to take difference between two times. i hope you understand above code.let me know is it ok or not...
Thanks.

get days starting from epoch

I want count of days starting from epoch(1970-01-01). I tried with joda-time
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = sdf.parse("2013-05-03 07:00:00");
Date date2 = sdf.parse("2013-05-03 23:30:00");
MutableDateTime epoch = new MutableDateTime();
epoch.setDate(0); //Set to Epoch time
System.out.println("Epoch: " + epoch);
Days days1 = Days.daysBetween(epoch, new MutableDateTime(date1.getTime()));
Days days2 = Days.daysBetween(epoch, new MutableDateTime(date2.getTime()));
System.out.println("1) Days Since Epoch: " + days1.getDays());
System.out.println("2) Days Since Epoch: " + days2.getDays());
} catch (ParseException e) {
e.printStackTrace();
}
and using logic:
// Create Calendar instance
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date);
// Set the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH.
// calendar1.set(calendar1.YEAR, calendar1.MONTH, Calendar.DAY_OF_MONTH);
calendar1.set(1970, 1, 1);
/*
* Use getTimeInMillis() method to get the Calendar's time value in
* milliseconds. This method returns the current time as UTC
* milliseconds from the epoch
*/
long miliSecondForDate1 = calendar1.getTimeInMillis();
long miliSecondForDate2 = calendar2.getTimeInMillis();
// Calculate the difference in millisecond between two dates
long diffInMilis = miliSecondForDate2 - miliSecondForDate1;
/*
* Now we have difference between two date in form of millsecond we can
* easily convert it Minute / Hour / Days by dividing the difference
* with appropriate value. 1 Second : 1000 milisecond 1 Hour : 60 * 1000
* millisecond 1 Day : 24 * 60 * 1000 milisecond
*/
long diffInSecond = diffInMilis / 1000;
long diffInMinute = diffInMilis / (60 * 1000);
long diffInHour = diffInMilis / (60 * 60 * 1000);
long diffInDays = diffInMilis / (24 * 60 * 60 * 1000);
if(logger.isInfoEnabled()) {
logger.info("Difference in Seconds : " + diffInSecond);
logger.info("Difference in Minute : " + diffInMinute);
logger.info("Difference in Hours : " + diffInHour);
logger.info("Difference in Days : " + diffInDays);
}
I am getting diff result for both of this. can somebody help where i am wrong.
thanks.
The difference between 17006 and 17007 is one day. This difference very likely comes from 7:00 and 23:30 in your time zone are on different days in some other time zone, say, UTC. Or the other way around, those times in UTC happen to be on different days in your time zone. Therefore the count is off by one. I don’t know JodaTime, so I cannot give you the precise details.
The difference between 16975 and 17006 is 31 days or a full month. I can tell you exactly where this comes from. Calendar months are 0-based: January is month 0, February is 1, etc. So calendar1.set(1970, 1, 1) sets your Calendar to February 1, 1970, 31 days after the epoch. Use calendar1.set(1970, Calendar.JANUARY, 1) instead. You will also want to control the hours, minutes and seconds of the Calendar. You may call clear() before set() to make sure the time is at midnight.
If you can use Java 8, you may do:
DateTimeFormatter format = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
OffsetDateTime t1 = LocalDateTime.parse("2013-05-03 07:00:00", format)
.atOffset(ZoneOffset.UTC);
OffsetDateTime t2 = LocalDateTime.parse("2013-05-03 23:30:00", format)
.atOffset(ZoneOffset.UTC);
System.out.println("1) Days Since Epoch: " + ChronoUnit.DAYS.between(Instant.EPOCH, t1));
System.out.println("2) Days Since Epoch: " + ChronoUnit.DAYS.between(Instant.EPOCH, t2));
This prints:
1) Days Since Epoch: 15828
2) Days Since Epoch: 15828
If you want to use a different time zone:
DateTimeFormatter format = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
ZonedDateTime t1 = LocalDateTime.parse("2013-05-03 07:00:00", format)
.atZone(ZoneId.systemDefault());
ZonedDateTime t2 = LocalDateTime.parse("2013-05-03 23:30:00", format)
.atZone(ZoneId.systemDefault());
System.out.println("1) Days Since Epoch: " + ChronoUnit.DAYS.between(Instant.EPOCH, t1));
System.out.println("2) Days Since Epoch: " + ChronoUnit.DAYS.between(Instant.EPOCH, t2));
You can fill in the desired time zone instead of ZoneId.systemDefault().

Calculating the time difference between two time stamp object - java

I am having java.sql.date and java.sql.time objects, I need to find the time duration between the dates.
So i am creating java.sql.timestamp object by using above date and time object
Timestamp timestamp1 = new Timestamp(StartDate.getYear(),
StartDate.getMonth(), StartDate.getDay(),
StartTime.getHours(), StartTime.getMinutes(), 00,
00);
Here is mycode
String date = "2010-01-05";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date3 = null;
try {
date3 = sdf1.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
Date StartDate = new Date(date3.getTime());
System.out.println("Date " + StartDate);
String date2 = "2010-01-06";
java.util.Date date4 = null;
try {
date4 = sdf1.parse(date2);
} catch (ParseException exception) {
exception.printStackTrace();
}
Date EndDate = new Date(date4.getTime());
System.out.println("Date " + EndDate);
String time = "01:00";
DateFormat formatter = new SimpleDateFormat("HH:mm");
java.sql.Time StartTime = null;
try {
StartTime = new java.sql.Time(formatter.parse(time).getTime());
} catch (ParseException exception2) {
exception2.printStackTrace();
}
System.out.println("TIMEEEEEEEEEE====" + StartTime);
String time2 = "02:00";
java.sql.Time EndTime = null;
try {
EndTime = new java.sql.Time(formatter.parse(time2).getTime());
} catch (ParseException exception3) {
exception3.printStackTrace();
}
System.out.println("TIMEEEEEEEEEE====" + EndTime);
Timestamp timestamp1 = new Timestamp(StartDate.getYear(),
StartDate.getMonth(), StartDate.getDay(),
StartTime.getHours(), StartTime.getMinutes(), 00,
00);
Timestamp timestamp2 = new Timestamp(EndDate.getYear(),
EndDate.getMonth(), EndDate.getDay(),
EndTime.getHours(), EndTime.getMinutes(), 00, 00);
long milliseconds = timestamp2.getTime() - timestamp1.getTime();
int seconds = (int) milliseconds / 1000;
// calculate hours minutes and seconds
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
seconds = (seconds % 3600) % 60;
System.out.println(hours+"h:"+minutes+"m:"+"00s");
Test case
when I give date as 2010-01-05 and date2 as 2010-01-06 I am getting output as below
Date 2010-01-05
Date 2010-01-06
TIMEEEEEEEEEE====01:00:00
TIMEEEEEEEEEE====02:00:00
25h:0m:00s
when I give date as 2010-01-05 and date2 as 2010-01-11 I am getting output in negative value as below
Date 2010-01-05
Date 2010-01-11
TIMEEEEEEEEEE====01:00:00
TIMEEEEEEEEEE====02:00:00
-23h:0m:00s
Help me to correct if I am doing something wrong.
Thanks in advance.
Manual time calculation:-
Converts Date in milliseconds (ms) and calculate the differences between two dates, with following rules :
1000 milliseconds = 1 second
60 seconds = 1 minute
60 minutes = 1 hour
24 hours = 1 day
Sample Example:-
package com.dps2.practice.dyuti;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDifferentExample {
public static void main(String[] args) {
String dateStart = "08/11/2016 09:29:58";
String dateStop = "08/12/2016 10:31:48";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
The problem with your calculation is this: StartDate.getDay() etc.
getDay() will return the number of day of the week (read the JavaDoc) and not the day of the month. You'll need to use getDate() instead.
To illustrate the problem using your values: 2010-01-05 will return 2 for getDay() and thus you are getting 2010-01-02 as your timestamp. 2010-01-11 will return 1 for getDay() (it's 6 days later, i.e. (2 + 6) % 7 = 1) and hence your second timestamp becomes 2010-01-01. Now the second timestamp is before the first and hence you get a negative value.
However, as I already stated in my comments you should try and use some library or at least the non-deprecated built-in functionality for those calculations to save you a lot of headaches (I suggest you watch this video to get an idea of the challenges: https://youtube.com/watch?v=-5wpm-gesOY ).
The java.sql date-time classes are meant only for exchanging data with databases. Do not use them for business logic. Also, they are part of the troublesome, poorly designed, and confusing old legacy date-time classes. Avoid them all.
java.time
The java.time classes built into Java 8 and later supplant the old classes you are using. Much simpler now.
LocalDate ld = LocalDate.parse ( "2010-01-06" );
LocalTime lt = LocalTime.parse ( "01:00" );
LocalDateTime earlier = LocalDateTime.of ( ld , lt );
LocalDateTime later = earlier.plusHours ( 7 );
The Duration class represents a span of time as a total number of seconds and nanoseconds. Its toString method generates a String in the standard ISO 8601 format PnYnMnDTnHnMnS. This format uses P to mark the beginning, and the T to separate year-months-days from hours-minutes-seconds portion. The Duration and Period classes can both parse and generate such Strings.
Duration duration = Duration.between ( earlier , later );
In Java 8, Duration class inexplicably lacks getter methods for each part: days, hours, minutes, seconds, fraction-of-second. Java 9 rectifies this omission with new getPart methods.
Dump to console.
System.out.println ( "earlier: " + earlier + " | later: " + later + " | duration: " + duration );
earlier: 2010-01-06T01:00 | later: 2010-01-06T08:00 | duration: PT7H
Time zone
Be aware that your inputs lacked any information about offset-from-UTC or time zone. So the math seen above is performed assuming generic 24-hour days. Real-world anomalies such as Daylight Saving Time (DST) are ignored.
If you did indeed intend time zones, assign them via the atZone method to instantiate OffsetDateTime or ZonedDateTime objects.
That's a complicated code you have in your question there. You can make it quite easy by using java.util.concurrent.TimeUnit class.
Output
Date Tue Jan 05 00:00:00 UTC 2010
Date Wed Jan 06 00:00:00 UTC 2010
difference is:
24 hours : 1440 minutes : 86400 seconds
Code
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
public class HelloWorld {
public static void main(String[] args) {
String date = "2010-01-05";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date3 = null;
try {
date3 = sdf1.parse(date);
} catch (Exception e) {
e.printStackTrace();
}
Date StartDate = new Date(date3.getTime());
System.out.println("Date " + StartDate);
String date2 = "2010-01-06";
java.util.Date date4 = null;
try {
date4 = sdf1.parse(date2);
} catch (Exception exception) {
exception.printStackTrace();
}
Date EndDate = new Date(date4.getTime());
System.out.println("Date " + EndDate);
long dateStart = StartDate.getTime(), dateStop = EndDate.getTime();
long diff = dateStop - dateStart;
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(diff);
long diffInHours = TimeUnit.MILLISECONDS.toHours(diff);
System.out.println("\n\ndifference is:\n");
System.out.println(diffInHours + " hours : " + diffInMinutes + " minutes : " + diffInSeconds + " seconds");
}
}

Time manipulation

Given the assignment t = System.currentTimeMillis(), accrued at some point in the past, how do I get the millis of the same day as t in 12 pm and the day after 12 pm?
Note: this is timezone dependent. You can do as such:
import static java.util.Calendar.*;
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(yourValue);
cal.set(HOUR_OF_DAY, 12);
cal.set(MINUTE, 0);
cal.set(SECOND, 0);
cal.set(MILLISECOND, 0);
// cal.getTimeInMillis() contains the wanted day at 12pm
cal.add(DAY_OF_YEAR, 1);
// cal.getTimeInMillis() now contains the wanted day plus one at 12pm
But do yourself a favour and use Joda Time, it is much easier to use in this case:
final DateTime dayAt12pm = new DateTime(yourValue).toDateMidnight()
.plusHours(12);
// dayAt12pm.getMillis() contains the wanted day at 12pm
// next day at 12pm: dayAt12pm.plusDays(1).getMillis()
//plug your "T" here.
long t = System.currentTimeMillis();
Date date = new Date(t);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Calendar startOfDay = Calendar.getInstance();
startOfDay.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
startOfDay.set(Calendar.HOUR, 12);
startOfDay.set(Calendar.MINUTE, 0);
startOfDay.set(Calendar.SECOND, 0);
startOfDay.set(Calendar.MILLISECOND, 0);
Date startOfDayDate = startOfDay.getTime();
System.err.println("12PM on time t is " + startOfDayDate);
startOfDay.add(Calendar.HOUR, 24);
startOfDayDate = startOfDay.getTime();
System.err.println("12PM day after t is " + startOfDayDate);
One way would be to create a Date from it and then use the Calendar class.

Get the number of milliseconds since some date

How to get the number of milliseconds from October 15th 2011 1:52:34 P.M.
I can get the number of milliseconds from the current time.
Date date = new Date();
long currentTime = date.getTime();
System.out.println("Current time in long: " + currentTime);
long now = System.currentTimeMillis(); // Simpler way to get current time
Date date = new SimpleDateFormat("dd yyyy h:mm:ss a").parse("15 2011 1:52:34 PM");
long timeElapsed = now - date.getTime(); // Here's your number of ms
Use the Calendar API. Then set the month, date and the time you want (October 15, 2011).
To get you started look into this:
Calendar c = Calendar.getInstance();
Hope this helps!
Link
import java.util.Calendar;
import java.util.Date;
public class TimeMilisecond {
public static void main(String[] argv) {
long lDateTime = new Date().getTime();
System.out.println("Date() - Time in milliseconds: " + lDateTime);
Calendar lCDateTime = Calendar.getInstance();
System.out.println("Calender - Time in milliseconds :" + lCDateTime.getTimeInMillis());
}
}
You could use SimpleDateFormat to parse an arbitrariy date and get the difference in ms.
Use java.util.Calendar and fill it with your date information. Then use java.util.Calendar.getTimeInMillis() to get the number of milliseconds since epoch.

Categories

Resources