Java date/calendar ignoring time zone [duplicate] - java

This question already has answers here:
Date and time conversion to some other Timezone in java
(11 answers)
Closed 8 years ago.
How to ignore timezone in dates? I mean I seted some jsf input with 8:54 with format HH:mm, and in setter I am getting 9:54, i Think that is because of time zone GMT+1. How to convert this date to ignore time zone? How to convert it when i dont know from which time zone I am using it.
code, setter of time picker input:
public void setDateTest(Date hmm){
if (hmm!=null){
int a = hmm.getHours();
int b = hmm.getMinutes();
Calendar cal = Calendar.getInstance();
cal.get(Calendar.ZONE_OFFSET);
cal.setTime(hmm);
int a2 = cal.get(Calendar.HOUR);
int c2 = cal.get(Calendar.HOUR_OF_DAY);
int b2 = cal.get(Calendar.MINUTE);
}
}

if you are using java.util.Calendar (probably you are), Hour index is in range between 0-11
http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#HOUR
so if you are giving 8 for Calendar.HOUR, this is actually 9. This might be the cause. Just an opinion...

Related

Easiest way to set past/future date in Java 8 [duplicate]

This question already has an answer here:
Setting future date in Java 8
(1 answer)
Closed 4 years ago.
I have a solution for setting future/past date Java 8, but I would like to know if there is a cleaner way.
I have a method in which one of the argument is of type ZonedDateTime.
I am extracting the time, converting to milliseconds and subtracting that from present now.
void setFuturePastDate(ZonedDateTime dateTime) {
long diffInSeconds = ZonedDateTime.now().toEpochSecond()
- dateTime.toEpochSecond();
Duration durationInSeconds = Duration.ofSeconds(diffInSeconds);
Instant instantInSeconds = now.minusSeconds(durationInSeconds);
Clock clock = Clock.fixed(instantInSeconds, ZoneId.systemDefault());
System.out.println(ZonedDateTime.now(clock)); // - I have a past date
In Joda it was simple:
setCurrentMillisSystem(long)
and wherever we access new DateTime() it will give the date set.
Is there a cleaner way in Java 8 ?
void setFuturePastDate(ZonedDateTime dateTime) {
Clock clock = Clock.fixed(dateTime.toInstant(), ZoneId.systemDefault());
System.out.println(ZonedDateTime.now(clock)); // - I have a past date
}
This method prints the same ZonedDateTime as I passed in (provided it has the default zone).
If I understood you correctly, this is what you want:
void setFuturePastDate(LocalDateTime dateTime){
final LocalDateTime now = LocalDateTime.now();
final Duration duration = Duration.between(now, dateTime);
final LocalDateTime mirrored;
if(duration.isNegative()){
mirrored = now.minus(duration);
} else {
mirrored = now.plus(duration);
}
System.out.println(mirrored);
}
This mirrors the dateTime around the now(). E.g: 5 days in the past becomes 5 days in the future.

get yesterday date from timestamp [duplicate]

This question already has answers here:
Get yesterday's date using Date [duplicate]
(8 answers)
Closed 8 years ago.
I've got an object with a field timestamp with type java.sql.Timestamp;.
And I need to get objects with yesterday date from a collection.
How to get them?
I mean I need something like this
for(int i = 0; i < items.size(); i++) {
(if the items.get(i).date == yesterday_date)
(get object)
}
You can get yesterday's Date by following approach Answered by Jiger Joshi.
And by using new Timestamp(java.util.Date) you can get yesterday's timestamp, you should use Timestamp#equals to equaling two different timestamp.
if (items.get(i).date.equals(getYesterdaytimestamp())){
...
}
And there are something which you must consider while implementing this. Calender#getTime which returns Date object and date object contains date with time, so in that case your equaling date or timestamp must be exactly equals with yesterday's date and time.
If requirement is, it needs to equal just yesterday no not where time is not considerable fact. In that case you need to equals two timestamp after discarding time part.
if (equalsWithYesterday(items.get(i).date)){
...
}
...
public boolean equalsWithYesterday(Timestamp st){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); // Time part has discarded
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
Date yesterday = dateFormat.parse(dateFormat.format(cal.getTime())); // get yesterday's Date without time part
Date srcDate = new Date(st);
Date srcDateWithoutTime =dateFormat.parse(dateFormat.format(srcDate));
return yesterday.equals(srcDateWithoutTime ); // checks src date equals yesterday.
}
You can convert the timestamp object to date object like this:
Date date = new Date(items.get(i).getTime());
or you can simply use method Timestamp#compareTo(Date o)
items.get(i).compareTo(yesterday_date);
I hope you are not interested to compare the time?
Simply use Calendar class to extract the day, month, year etc. from the date and simply compare it.
Use Calendar#get() method to get the specific field from the date object.
How to subtract one day from the current date?
// get Calendar with current date
Calendar cal = Calendar.getInstance();
// get yesterday's date
cal.add(Calendar.DATE, -1);
// get components of yesterday's date
int month = cal.get(Calendar.MONTH) + 1; // 0 for January, 1 for Feb and so on
int day = cal.get(Calendar.DATE);
int year = cal.get(Calendar.YEAR);
// get yesterday's date in milliseconds
long lMillis = cal.getTime().getTime();

How to subtract an hour from current timestamp [duplicate]

This question already has answers here:
Changing Java Date one hour back
(11 answers)
Closed 9 years ago.
How to subtract an hour from current time-stamp?
Calendar c = Calendar.getInstance();
System.out.println("current: "+c.getTime());
Add -1 to the Calendar.HOUR attribute:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR, -1);
Oh! And with Joda Time, there you go:
DateTime date = DateTime.now();
DateTime dateOneHourBack = date.minusHours(1);
Although difference might not be visible here, but it's a much more simple and better API than Date and Calendar in JDK.
The answer you are looking for is
cal.add(Calendar.HOUR, -numberOfHours);
where numberOfHours is the amount you want to subtract.
You can also refer this link for more information
http://examples.javacodegeeks.com/core-java/util/calendar/add-subtract-hours-from-date-with-calendar/
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, -1);
Add -1
add(int field,int amount)
Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 1 hours from the current time of the calendar, you can achieve it by calling:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -1);
call add() method with a negative parameter if you want to subtract and positive parameter if you want to add the hour.
for adding 2 hours,
calendar.add(Calendar.Hour,2);
for subtracting 3 hours,
calendar.add(Calendar.Hour,-3);

Find difference between two time in java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to convert Milliseconds to “X mins, x seconds” in Java?
Calculating the Difference Between Two Java Date Instances
I have a function like this:
public String setDateAndTime(int h, int m, int s,int amPm) {
TimeZone nst = TimeZone.getTimeZone("GMT+5:45");
Calendar calendar1 = new GregorianCalendar(nst);
Date currentTime1 = new Date();
calendar1.setTime(currentTime1);
calendar1.set(Calendar.HOUR, h);
calendar1.set(Calendar.MINUTE, m);
calendar1.set(Calendar.SECOND, s);
calendar1.set(Calendar.YEAR, calendar1.get(Calendar.YEAR));
calendar1.set(Calendar.MONTH, calendar1.get(Calendar.MONTH));
calendar1.set(Calendar.DAY_OF_MONTH, calendar1.get(Calendar.DAY_OF_MONTH));
calendar1.set(Calendar.AM_PM, amPm);
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
String date = formatter.format(calendar1.getTime());
return date;
}
Through this function i created two dates(String)
String s1=setDateAndTime(12,00,00,1);//12:00:00 PM
String s2=setDateAndTime(3,15,45,0);//3:15:45 AM
Now how to find to find difference between s1 and s2, i also need the hours, minutes and second lefts, so that i can do further processing.
You can get time in milliseconds by calling getTime(). Then compare long values.
milliis/1000 gives seconds, millis/60/1000 gives minutes, millis/3600/1000 gives hours, etc.
You can also use 3rd party libraries like JodaTime but if you need this one-time Joda is too much.

Convert String dates into Java Date objects [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Calculating difference in dates in Java
How can I calculate a time span in Java and format the output?
Say you were given two dates as strings and they are in this format 8/11/11 9:16:36 PM how would I go about converting them to java Date objects so that I can then calculate the difference between two dates?
As long as both times are in GMT/UTC, you can do date1.getTime() - date2.getTime() and then divide the result by 86400000 to get number of days. The rest is probably pretty intuitive.
EDIT -- based on edited question
To convert Strings into dates, use the SimpleDateFormat class.
String yourDateString = "8/11/11 9:16:36 PM";
SimpleDateFormat format =
new SimpleDateFormat("MM/dd/yy HH:mm:ss a");
Date yourDate = format.parse(yourDateString);
The majority of Date's getters are deprecated, replaced with Calendar methods. Here's how you would do it
Date date1, date2; //initialized elsewhere
Calendar day1 = new Calendar();
day1.setTime(date1)
Calendar day2 = new Calendar();
day2.setTime(date2);
int yearDiff, monthDiff, dayDiff, hourDiff, minuteDiff, secondDiff;
yearDiff = Math.abs(day1.get(Calendar.YEAR)-day2.get(Calendar.YEAR));
monthDiff = Math.abs(day1.get(Calendar.MONTH)-day2.get(Calendar.MONTH));
dayDiff = Math.abs(day1.get(Calendar.DAY_OF_YEAR)-day2.get(Calendar.DAY_OF_YEAR));
hourDiff = Math.abs(day1.get(Calendar.HOUR_OF_DAY)-day2.get(Calendar.HOUR_OF_DAY));
minuteDiff = Math.abs(day1.get(Calendar.MINUTE)-day2.get(Calendar.MINUTE));
secondDiff = Math.abs(day1.get(Calendar.SECOND)-day2.get(Calendar.SECOND));
Then you can do whatever you like with those numbers.
define a SimpleDateFormat matching your format (the java doc is pretty straighforward), then use the parse method to get a the proper Date object, from which you can easily compute the difference between the two dates.
Once you have this difference, the best is probably to compute "manually" the number of days / hours / minutes / seconds, although it might be possible to again use a SimpleDateFormat (or some other formatting mechanism) to display the proper values in a generic way.

Categories