Is there any way to update only a Date's time path?
I tried Date.setTime() but it replaces the date path too. I there any java method or the only way is to set hour, minute, second and milisecond?
Thank you
A Java Date is just a wrapper around a long that counts time from the epoch (January 1, 1970). Much more flexible is Calendar. You can create a Calendar from a Date:
Date date = . . .;
Calendar cal = new GregorianCalendar();
cal.setTime(date);
Then you can set various fields of the Calendar:
cal.set(Calendar.HOUR_OF_DAY, 8);
// etc.
I would start by moving away from java.util.Date entirely. Ideally, use Joda Time as it's a far more capable date/time library.
Otherwise, you should use java.util.Calendar. A java.util.Date doesn't have a particular date/time until you decide what time zone you're interested in - it just represents an instant in time, which different people around the world will consider to be a different date and time of day.
You'll want to take a look at java.util.Calender.
It will allow you to change the individual parts of the date/time.
Calendar cal = Calender.getInstance();
cal.setTime(date);
cal.set(Calender.HOUR, hour);
Alternatively, as has already being suggested, I'd take a look at Joda Time
Related
I have a problem in java. I have a calendar in my java program and I want to set time zone to my local time zone.
I was able do do this and it works very well. My problem is when I change time zone in calendar time format in calendar change to 12H from 24H and i don't want this!
my question is How to change time zone in calendar without changing my time format in java?
this is my code for time zone change :
public static Calendar setTimeZoneToTehran(Calendar calendar) {
TimeZone timeZoneOfTehran = TimeZone.getTimeZone("Asia/Tehran");
calendar.setTimeZone(timeZoneOfTehran);
return calendar;
}
Just a quick thought, in case you are using time format to read/parse purpose you can use SimpleDateFormat to the desired format.
Date date = calendar.getTime();
System.out.println(format.format(date));
As #devilpreet already said, formatting in Calendar is only additional, bonus feature. This class is designed to keep info about date and time, formatting of date is encapuslated in SimpleDateFormat class.
Moreover, consider using Joda Time or java.time(from Java 8) instead of java.util.Calendar(in some circles using java.util.Calendar and Date is considered a bad practice).
I have a GUI that plots time-series graphs. The user enters the dates they want to plot from and to by entering values in text boxes. For example, if they enter 25/07/13 22:00 and 26/07/13 00:00 the graph should plot data from 22:00:00 on the 25th through to 00:00:59 the following morning. The times the user enters are parsed into a Calendar object.
My problem comes with DST.
The user doesn't care about DST, so all they want to see is a graph between those two times. However, the Calendar objects do care about DST and so my "to" date is currently not 00:00, but 01:00. (I am in London and we are currently GMT + 1 hour for DST).
I want to effectively ignore DST and act as though everything is GMT + 0 when I want to plot graphs.
How can I do this?
Thanks for the answers guys, they helped me get my head around the problem. It sort of comes down to the fact that I use both the Calendar object, for presentation and storage of data, and the epoch for temporal calculations.
It turns out that the Calendar set() methods will take into account DST as a matter of course. So when I parse the time values in the text boxes that the user enters, and use set() for each individual Calendar field, the Calendar object will know, based-off historical data, whether the date you've just set will have DST applied. Because of this, it understands that you meant, for example, GMT+1, even if you didn't realise it (because, frankly, who does?!).
However, when you do getTimeInMillis(), the epoch returned has no concept of time zones or DST, so to match with the current time zone you have to apply DST manually to the returned epoch, if it applies. Conversely, when you use setTimeInMillis() on a Calendar object, it is assumed that the time you entered is GMT+0, but if the epoch is a date that currently has DST applied, the Calendar object will add it on for you, meaning you're +1 hour from where you thought you were. To solve this problem, you need to subtract DST, again if necessary, from the epoch before setting it in the calendar.
All of this confusion is particularly important on day boundaries, especially if you're using day resolution for anything, like me.
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.DST_OFFSET, 0);
If I understand you correctly you need to parse 25/07/13 22:00 as GMT date/time:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = sdf.parse("25/07/13 22:00");
and make a Calendar based on this date
Calendar c= Calendar.getInstance();
c.setTime(date);
TimeZone tz = TimeZone.getTimeZone("Etc/GMT0");
DateFormat df = DateFormat.getDateTimeInstance();
df.setTimeZone(tz);
System.out.println(df.format(new Date()));
Hi I want to iterate through a date range without using any libraries. I want to start on 18/01/2005(want to format it to yyyy/M/d) and iterate in day intervals until the current date. I have formatted the start date, but I dont know how I can add it to a calendar object and iterate. I was wondering if anyone can help. Thanks
String newstr = "2005/01/18";
SimpleDateFormat format1 = new SimpleDateFormat("yyyy/M/d");
Date date = format1.parse(newstr);
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
while (someCondition(calendar)) {
doSomethingWithTheCalendar(calendar);
calendar.add(Calendar.DATE, 1);
}
Use SimpleDateFormat to parse a string into a Date object or format a Date object into a string.
Use class Calendar for date arithmetic. It has an add method to advance the calendar, for example with a day.
See the API documentation of the classes mentioned above.
Alternatively, use the Joda Time library, which makes these things easier. (The Date and Calendar classes in the standard Java API have a number of design issues and are not as powerful as Joda Time).
I have a mobile application where I capture a date/time and send it as miliseconds to a servlet. -For example I capture 12:55 AM in my cellphone and send it to my server-
So, I construct the date from the sent miliseconds and print it with SimpleDateFormat but the time is diferent, it prints 8:55 AM.
I know that the problem is because I use 2 diferent timezones, my question is:
how can I show that time without apply any timezone to show the same time?
Thanks in advance
You need to use Calendar to change the TimeZone but there is no API for that.
// Change a date in another timezone
public static Date changeTimeZone(Date date, TimeZone zone) {
Calendar first = Calendar.getInstance(zone);
first.setTimeInMillis(date.getTime());
Calendar output = Calendar.getInstance();
output.set(Calendar.YEAR, first.get(Calendar.YEAR));
output.set(Calendar.MONTH, first.get(Calendar.MONTH));
output.set(Calendar.DAY_OF_MONTH, first.get(Calendar.DAY_OF_MONTH));
output.set(Calendar.HOUR_OF_DAY, first.get(Calendar.HOUR_OF_DAY));
output.set(Calendar.MINUTE, first.get(Calendar.MINUTE));
output.set(Calendar.SECOND, first.get(Calendar.SECOND));
output.set(Calendar.MILLISECOND, first.get(Calendar.MILLISECOND));
return output.getTime();
}
Link: http://blog.vinodsingh.com/2009/03/date-and-timezone-in-java.html
I think this should work. I haven't extensively tested it.
Calendar and Date objects store their date information in milliseconds in relation to UTC.
(the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC)
This means that Calendar/Date Objects do not store different values for different Time Zones. They always use the same value internally... the format is what normally changes.
Maybe you can use a SimpleDateFormat in your local/default timezone:
SimpleDateFormat sdf = new SimpleDateFormat("S")
Date d = sdf.parse(milliseconds);
You can also try to change the DateFormat's timezone until it matches your expected output.
sdf.setTimeZone(TimeZone.getTimeZone("GMT-8"));
System.out.println(sdf.toString());
sdf.setTimeZone(TimeZone.getTimeZone("GMT-4"));
System.out.println(sdf.toString());
This question already has answers here:
How can I get the current date and time in UTC or GMT in Java?
(33 answers)
Closed 6 years ago.
Since java.util.Date is mostly deprecated, what's the right way to get a timestamp for a given date, UTC time? The one that could be compared against System.currentTimeMillis().
Using the Calendar class you can create a time stamp at a specific time in a specific timezone. Once you have that, you can then get the millisecond time stamp to compare with:
Calendar cal = new GregorianCalendar();
cal.set(Calendar.DAY_OF_MONTH, 10);
// etc...
if (System.currentTimeMillis() < cal.getTimeInMillis()) {
// do your stuff
}
edit: changed to use more direct method to get time in milliseconds from Calendar instance. Thanks Outlaw Programmer
The "official" replacement for many things Date was used for is Calendar. Unfortunately it is rather clumsy and over-engineered. Your problem can be solved like this:
long currentMillis = System.currentTimeMillis();
Date date = new Date(currentMillis);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
long calendarMillis = calendar.getTimeInMillis();
assert currentMillis == calendarMillis;
Calendars can also be initialized in different ways, even one field at a time (hour, minute, second, etc.). Have a look at the Javadoc.
Although I didn't try it myself, I believe you should take a look at the JODA-Time project (open source) if your project allows external libs.
AFAIK, JODA time has contributed a lot to a new JSR (normally in Java7) on date/time.
Many people claim JODA time is the solution to all java.util.Date/Calendar problems;-)
Definitely worth a try.
Take a look at the Calendar class.
You can make a Data with the current time (not deprecated) and then make Calendar from that (there are other ways too).