I have an
i) integer variable called gmtoffset (which is the number of hours/minutes to add/subtract from the base time) and
ii) map object(called result) which contains the timestamp in GMT . I need to iterate into map object and change the timestamp inside the map object by adding/subtracting according to the no of hours in gmtoffset variable.
For e.g, int gmtoffset = 0230 , changedTimestamp = 2013-09-11 01:11:00.1
My final changedTimestamp variable should be 2013-09-11 10:41:00.1
Request help.
You can use a Java Calendar and SimpleDateFormat to do the job. Something like the following:
Date date = <convert your changedTimesetamp to a date, see SimpleDateFormat>
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.setTime(date);
cal.add(Calendar.MINUTE, gmtoffset);
Note: Assuming gmtoffset is express in minutes... so 2 hours and 30 minutes would be 150 minutes.
Related
I want to compare time difference in hours. Based on current time and time I get from database.
DateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
Date date = new Date();
Logger.info(“current time is”,sdf.format(date));
// gives date in 2019-11-06 17:03:54
// dB gives following record
Date successDate = loader.getLastSuccess();
// gives date in 2019-10-31T:56:08.066+0000
Both formats are different how to get the time difference any suggestion experts
You can use the java-8 date API Duration to get the duration between both the dates
long hours = Duration.between(date1.toInstant(), date2.toInstant()).toHours();
Note : It can return negative value also here
the number of hours in the duration, may be negative
public int getHours() on util.Date is deprecated, so convert them to Instant and use Duration.between and also i will suggest to use java-8 Date API instead of older version Date
If you want difference in hours as double, you can do this;
Date your_date = loader.getLastSuccess();
Date currentDate = new Date();
double hourdifference = (currentDate.getTime() - your_date.getTime()) / 3600000.0;
You can get long or int, just change 3600000.0 to 3600000, and make the variable int or long
I need to write a function that accepts a java.util.Date and removes the hours, minutes, and milliseconds from it USING JUST MATH (no Date formatters, no Calendar objects, etc.):
private Date getJustDateFrom(Date d) {
//remove hours, minutes, and seconds, then return the date
}
The purpose of this method is to get the date from a millisecond value, without the time.
Here's what I have so far:
private Date getJustDateFrom(Date d) {
long milliseconds = d.getTime();
return new Date(milliseconds - (milliseconds%(1000*60*60)));
}
The problem is, this only removes minutes and seconds. I don't know how to remove hours.
If I do milliseconds - (milliseconds%(1000*60*60*23)), then it goes back to 23:00 hrs on the previous day.
EDIT:
Here's an alternative solution:
public static Date getJustDateFrom(Date d) {
Calendar c = Calendar.getInstance();
c.setTime(d);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
return c.getTime();
}
Will this solution be affected by time zone differences between the client/server sides of my app?
There are 24 hours in a day. Use milliseconds%(1000*60*60*24).
Simply not possible by your definition.
A millisecond timestamp represents milliseconds elapsed from a fixed point in time (1970-01-01 00:00:00.000 UTC, if I remember correctly). This timestamp can not be converted into a date + time without specifying the timezone to convert to.
So you can only round the timestamp to full days in respect to a specific timezone, not in general. So any fiddling with Date.getTime() and not taking into account any timezone is guaranteed to work in only one time zone - the one you hardcoded for.
Do yourself a favor and use a Calendar.
You can make use of apache's commons lang DateUtils helper utility class.
For example, if you had the datetime of 28 Mar 2002
13:45:01.231, if you passed with Calendar.HOUR, it would return 28 Mar
2002 13:00:00.000. If this was passed with Calendar.MONTH, it would
return 1 Mar 2002 0:00:00.000.
Date newDate = DateUtils.truncate(new Date(1408338000000L), Calendar.DAY_OF_MONTH);
You can download commons lang jar at http://commons.apache.org/proper/commons-lang/
import java.sql.Date;
long dateInEpoch = 1_592_283_050_000L;
ZoneId defaultZoneId = ZoneId.systemDefault();
long currentDate = Date
.from(new Date(dateInEpoch)
.toLocalDate()
.atStartOfDay(defaultZoneId)
.toInstant())
.getTime();
input : 1592283050000
output: 1592245800000
Im trying to convert unixtime to date but the results im getting are wrong :
for example i have this unixtime : 1354312800 accurding to this site :
enter link description here
the result is :
Fri, 30 Nov 2012 22:00:00 GMT
but when i do :
long timestamp = 1354312800;
java.util.Date time=new java.util.Date((long)timestamp*1000);
int d = time.getDay();
int m = time.getMonth();
im getting :
d= 6 << this is wrong should be 30.
and m - 11
You have mistaken getDay()for getDate().
getDay Javadoc:
Returns the day of the week represented by this date. The returned value (0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday) represents the day of the week that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.
So just use getDate() instead of getDay()
For more info, check the javadoc: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html
If your time still differs from the Unix time you tried, you are probably living not in the GMT Timezone, so you need to find out the date for the corresponding timezone:
SimpleDateFormat df = new SimpleDateFormat();
df.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(df.format(time));
This should give you the expected output, even though your local tiemzone differs from GMT
The method Date.getDay() gives the day of the week (0 = Sunday, ..., 6 = Saturday).
Change it to Date.getDate() and you will get 30 as the result.
Some side-notes:
The Date class is pretty much deprecated. Use Calendar instead, or even better, the Joda time library.
Your conversion is sort of funny. (long)timestamp*1000 converts timestamp to a long value (which is already a long value) and then automatically widens 1000 to a long value to carry out the multiplication.
I would skip the conversion, (long) , altogether, and if you want to explicitly say that the factors are long values, use 1000L instead, which is a long-literal.
i'm retrieving a strange result:
First i get current date using GregorianCalendar:
GregorianCalendar g = new GregorianCalendar();
int m = g.get(Calendar.DAY_OF_MONTH);
int d = g.get(Calendar.DAY_OF_WEEK);
int y = g.get(Calendar.YEAR);
Then i create new object Date:
Date d = new Date(d,m,y);
Then i print them together in this way:
System.out.println(d+" - "+m+" - "+y+" - "+d);
and i get:
1 - 18 - 2012 - Thu Jan 02 00:00:00 CET 1908
can you explain me why? is for deprecated method Date(day,mouth,year) ?
if yes, how can i compare two Date using that parameters?
Then i create new object Date:
Date d = new Date(d,m,y);
The order of the arguments to the constructor is year, month, date, nothing else.
From the documentation:
Date(int year, int month, int day)
how can i compare two Date using that parameters?
Depends on how you want to compare two Dates. If you just want to figure out which comes first, you could use Date.before and Date.after.
But as you've noted, the Date class is deprecated. Use the Calendar class instead, (or better yet, the Joda Time library)
If you need to obtain a new Date object from a GregorianCalendar, do this:
Date d = g.getTime();
In this way, you won't have to use deprecated methods, and the result will be the one you expect. Also, if you need to obtain the current date, simply write new Date(), no need for a GregorianCalendar.
As far as date comparisons go, you can use Date's compareTo(), after() and before() methods. Again, there's no need for a GregorianCalendar.
Create a Calendar, then set the time using the Date object, then you can get any information you need from it.
Example:
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
int day = cal.get(Calendar.DAY_OF_MONTH);
// and so on....
My program needs to represent this date as a java.sql.date object , but it seems that when I create a new date (using the calendar) and set it to '9999-12-31' and finally convert this java.util.date object to a java.sql.date object, this date is converted to something like '000-01-31'.
Calendar calendar = Calendar.getInstance();
calendar.set(9999, 12, 31);
infinityDate = new java.sql.Date(normalizeDate(calendar.getTime()).getTime());
infinityDate should be 31-12-9999
but when my code reaches here :
if(otherDate.equals(infinityDate))
{// Do stuff}
It never goes into the if condition as the infinityDate has for some reason been changed to 31-01-000, even though otherDate is infact '31-12-9999'.
The fact that otherDate is 31-12-9999 tells me that java can represent this dates , but for some reason , when I construct it using a calendar it changes the date. (otherDate comes from a jdbc statement which fetches data from a database)
This reference date '31-12-9999' has been fixed by some client , so it cannot be changed and my program has to be able to compare some incoming date values with this.
Does anyone know why this is happening , I realize that http://en.wikipedia.org/wiki/Year_10,000_problem may be a problem for dates after year 9999 , but I should be safe by a day.
EDIT : The Normalize date method only "normalizes the given date to midnight of that day"
private static java.util.Date normalizeDate(java.util.Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
date = calendar.getTime();
return date;
}
But , this issue was appearing before I was normalizing the date , I normalized it in an attempt to fix this.
Months are zero indexed. Use 11 for December, not 12. This is why you are rolling over the year.
Calendar.MONTH is zero-based. The call
calendar.set(9999, 12, 31);
sets the date to "the 31st day in the 13th month of the year 9999", which is then implicitly converted to the 1st month of the year 10000. It would result in an exception if you first called
calendar.setLenient(false);
Check hours, minutes, seconds and milliseconds that are held into these 2 date objects. I believe they are different.
If your want to compare the date (year, month, day) only you should probably create your custom Comparator and use it.