I want know to how can I identifies if there is a date changes i.e. 23:59 to 00:00.
I am using a servlet. I can do it using a static String type variable and assign it to "dd" part of below returned date stamp and comparing it on every request with the current "dd" date stamp. If both "dd" part do not match then it will be sign of date change. Actually there is one static int type variable that I want to reset to zero which increment till the day change.
private static String getDate()
{
SimpleDateFormat customFormat = new SimpleDateFormat("HH:mm:ss dd-MM-yyyy");
return customFormat.format(new Date(System.currentTimeMillis()));
}
But how can I do it without comparing it, is there any better way to do it? Thanks.
Related
When I do like below,
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
calendar.setTime(startTime); // startTime Date
DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);
I get Output like 2015-04-15T11:04:30.000Z.
I want it to be like 2015-04-15T11:04:30.000.
Is there a way to achieve this?
Accepted answer or my Java seems to be outdated because I received this error:
The method newXMLGregorianCalendar(String) in the type DatatypeFactory is not applicable for the arguments (SimpleDateFormat)
and I didn't want to extend, so I solved it by removing timezone:
xmlCalendar.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
If you want to remove only "Z" from XMLGregorianCalendar object just call this method.
xmlDate.setTimezone( DatatypeConstants.FIELD_UNDEFINED )
Do it as follow
DatatypeFactory df;
try {
df = DatatypeFactory.newInstance();
return df.newXMLGregorianCalendar(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));
} catch (DatatypeConfigurationException e) {
// throw new SomeRuntimeException(e);
}
Or Extend new class from XMLGregorianCalendar, override toXMLFormat and then delegate ALL the other methods to the contained instance.
class CustomXMLGregorianCalendar extends XMLGregorianCalendar
{
XMLGregorianCalendar calendar;
CustomXMLGregorianCalendar(XMLGregorianCalendar calendar){
this.calendar = calendar;
}
public String toXMLFormat() {
String text = calendar.toXMLFormat();
int pos = text.indexOf('Z');
return pos < 0 ? text : text.substring(0,pos);
}
public void setTimezone(int offset){ calendar.setTimezone( offset ); }
// ...
}
This is because your Locale Timezone, to achieve what you need transform the date using SimpleDateFormat:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
UPDATE when you comment:
I tried formatting it to a String then again parsing it to a Date. Then setting time in Calender object. Does not work. Still i get output as "2015-04-15T11:04:30.000Z"
You must understand that Calendar or Date objects are stored in it's own format, another thing is how you print them, so in this case, to see 2015-04-15T11:04:30.000Z in the Calendar representation does not matters, what you need is to have the correct date 2015-04-15 at 11:04:30 show this in the desired format is just to make user-friendly your output.
The output you get is from Calendar.toString() and the method doc says:
Return a string representation of this calendar. This method is intended to be used only for debugging purposes, and the format of the returned string may vary between implementations. The returned string may be empty but may not be null.
So in order to store the date and the time, your Calendar object is correct. In order to print it, you have to transform it into a String.
I had a similar issue. I'm putting this here for anyone that comes along after, but solved my issue similar to how Ignas Vaitekunas eventually did it.
I used
XMLGregorianCalendar xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());
xgc.setYear(year);
xgc.setMonth(month);
xgc.setDay(day);
xgc.setHour(hour);
xgc.setMinute(min);
xgc.setSecond(second);
xgc.setTimezone(timezone);
Where year, month, day, hour, min, second, timezone are all initially set to DatatypeConstants.FIELD_UNDEFINED.
I pull values from a formatted text field that's displayed to the user as ' - - T : : Z'. The user fills in what information they have, I split and parse the string and if I have a value for the timezone (or second, or minute, or hour etc) I set it, if not it gets fed to xgc as and undefined field. Then the XML Gregorian Calendar will print out only what values aren't undefined.
I had that situation and it was solved, using this line:
XMLGregorianCalendar dateNew = DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-09-06T21:08:14");
Can anyone tell me why the date is being set to next month instead of this month?
Even though im setting the dateFormatted variable as "28/08/2014" its setting the date to "28/07/2014".
I can simply go -1 at the month but it will mess up the date in January.
Is there some other way i should be setting the date?
Thanks
UtilDateModel model;
JDatePanelImpl datePanel;
DatePickerImpl datePicker;
model = new UtilDateModel();
model.setDate(yearInt, monthInt, dayInt);
model.setSelected(true);
datePanel = new JDatePanelImpl(model);
datePicker = new JDatePickerImpl(datePanel);
// String dateFormatted = (String) result[1];
String dateFormatted = "28/08/2014";
System.out.println("Date Formatted : " + (String) result[1]);
int day = Integer.parseInt(dateFormatted.substring(0, 2)); // Correct
int month = Integer.parseInt(dateFormatted.substring(3, 5)); // Correct
int year = Integer.parseInt(dateFormatted.substring(6, 10)); // Correct
System.out.println(day);
System.out.println(month);
System.out.println(year);
model.setDate(year, month, day);
model.setSelected(true);
You're doing date parsing wrong, please use a SimpleDateFormat or the like
The problem that you are seeing is probably related to the fact that some fields are 0-based and some are 1-based.
UPDATE
Dates should not be stored as strings in the database, instead use the available date types.
Date parsing in general is much trickier than you might think. DST, leap years, language,... all comes into play.
The newest java iteration has a complete rewrite for date handling based on joda time (http://www.joda.org/joda-time/) but you can also use the "old" way of date parsing in java which is not bad, simply different.
You should look at the javadoc of SimpleDateFormat, it will tell you why you need lower case "yyyy" for example and upper case "MM". The formatter will give you a Date which you can probe with Calendar for the required fields.
All the while it will take into account all the niggling details about date handling.
I'm not known with the 'JDatePicker' package, but after doing some research, i've found this, please read article 3 on this page. It says month number is 0 based, so januari should be 0 ( 1st month minus 1).
This question already has answers here:
Comparing two java.util.Dates to see if they are in the same day
(14 answers)
Closed 6 years ago.
I have a problem with Date instance. I did the following:
Date startDate = new Date(); //this is from database value
Date todayDate = new Date(); //this is created locally
Now when am trying to compare them, the only issue is that the Date instance will have time, so when I check if they are equal it probably wouldn't give the same thing I expect, but rather less or more. I tested the following:
System.out.println(rsv.startDate);
System.out.println("Today date:"+todayDate);
if(rsv.startDate.equals(todayDate)){
System.out.println("Equal!");
}else if(rsv.startDate.after(todayDate)){
System.out.println("After!!");
}else{
System.out.println("Before!!!!");
}
and although both are 5th feb but it shows output of Before instead of equal. How can I remedy this? I know about SimpleDateFormat but that would change the date to strings.
Thanks,
For Date operation you can use Joda utility. Following snippet code shows compare two date :
DateTime one = new DateTime(original-Date-1);
DateTime two = new DateTime(original-Date-2);
LocalDate oneDate = one.toLocalDate();
LocalDate twoDate = two.toLocalDate();
return oneDate.compareTo(twoDate);
You can see: http://joda-time.sourceforge.net/index.html
You can strip out the time from the current Date object:
Date date = new Date();
Calendar dCal = Calendar.getInstance();
dCal.setTime(date);
dCal.set(Calendar.HOUR_OF_DAY, 0);
dCal.set(Calendar.MINUTE, 0);
dCal.set(Calendar.SECOND, 0);
dCal.set(Calendar.MILLISECOND, 0);
date = dCal.getTime();
And then make your comparision.
Alternatively, if you need in your project more date/time processing power, you can use joda date time library: http://joda-time.sourceforge.net
MidnightDate class is suitable for this specific usecase: http://joda-time.sourceforge.net/api-release/org/joda/time/DateMidnight.html
Date contains both the date and time. Equals() will only return true if the time is also the same. To make the comparison work, you need to make sure that the time portion of both Date objects is the same (eg all set to zero).
This question already has answers here:
Java Date cut off time information
(20 answers)
Closed 8 years ago.
I want to implement a thread-safe function to remove the time part from java.util.Date.
I tried this way
private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
public static Date removeTimeFromDate(Date date) {
Date returnDate = date;
if (date == null) {
return returnDate;
}
//just have the date remove the time
String targetDateStr = df.format(date);
try {
returnDate = df.parse(targetDateStr);
} catch (ParseException e) {
}
return returnDate;
}
and use synchronized or threadLocal to make it thread-safe.
But it there any better way to implement it in Java. It seems this way is a bit verbose.
I am not satisfied with it.
A Date object holds a variable wich represents the time as the number of milliseconds since epoch. So, you can't "remove" the time part. What you can do is set the time of that day to zero, which means it will be 00:00:00 000 of that day. This is done by using a GregorianCalendar:
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
gc.set(Calendar.HOUR_OF_DAY, 0);
gc.set(Calendar.MINUTE, 0);
gc.set(Calendar.SECOND, 0);
gc.set(Calendar.MILLISECOND, 0);
Date returnDate = gc.getTime();
A Date holds an instant in time - that means it doesn't unambiguously specify a particular date. So you need to specify a time zone as well, in order to work out what date something falls on. You then need to work out how you want to represent the result - as a Date with a value of "midnight on that date in UTC" for example?
You should also note that midnight itself doesn't occur on all days in all time zones, due to DST transitions which can occur at midnight. (Brazil is a common example of this.)
Unless you're really wedded to Date and Calendar, I'd recommend that you start using Joda Time instead, as that allows you to have a value of type LocalDate which gets rid of most of these problems.
I need to write the high performance function which calculates the new datetime based on given datetime and timeshift. It accept 2 arguments:
String, representing the date in format YYYYMMDDHHmm
Integer, representing the timeshift in hours
Function returns the string in format of 1st argument which is composed as result of applying the timeshift to 1st argument
It is known in advance that the first argument is always the same during the program lifetime.
My implementation has the following steps:
parsing 1st argument to extract the year,month,date, hours,min
creating GregorianCalendar(year, month, date, hours, min) object
applying method GregorianCalendar.add(HOUR,timeshift)
applying SimpleDateFormat to convert result back into string
Issue is that I do not take advantage from the fact that 1st argument is always the same.
If I will create a class member GregorianCalendar(year, month, date, hours, min), then after the 1st call to my function this object will be modified, which is not good, because I cannot reuse it for the following calls.
If you can, use the Joda-Time library, which makes date arithmetic very simple:
DateTime dt = new DateTime();
DateTime twoHoursLater = dt.plusHours(2);
They have a DateTimeFormatter class that you'd use to do the parsing of your input date-time string into a DateTime, eg:
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMddHHmm");
DateTime dt = fmt.parseDateTime(myDateString);
DateTime result = dt.plusHours(myTimeshiftInHours);
And Joda-Time interoperates well with java.util.Date too. I love it!
If the first argument is a value that will not change often, perhaps use a cache :
static private Map<String,Calendar> dateCache = new HashMap<String,Calendar>();
Then, in your method, check of the first argument (ex: String dateStr) is a key in the cache
Calendar cal;
if (dateCache.containsKey(dateStr)) {
cal = (Calendar)(dateCache.get(dateStr)).clone();
} else {
// parse date
cal = new GregorianCalendar(...);
dateCache.put(dateStr, (Calendar)cal.clone());
}
And add your timeshift value.
How about this,
Parse and hold on to your fixed date, call it fixedDate
Let timeShift be a time shift in hours, then Date shiftedDate = new Date(fixedDate.getTime() + (timeShift * 3600000)) would be your calculated shifted date (see this and this for understanding)
Apply SimpleDateFormat to convert shiftedDate to string.
Repeat steps 2 and 3 indefinitely, fixedDate is not modified and can be reused.
I'd try simple memoisation:
// This is not thread safe. Either give each thread has its own
// (thread confined) converter object, or make the class threadsafe.
public class MyDateConverter {
private String lastDate;
private int lastShift;
private String lastResult;
public String shiftDate(String date, int shift) {
if (shift == lastShift && date.equals(lastDate)) {
return lastResult;
}
// Your existing code here
lastDate = date;
lastShift = shift
lastResult = result;
return result;
}
}
Note this simple approach is most effective if the shift and date values rarely change. If either changes frequently, you'd need a more complicated cache, the code will be more complicated and the overheads (for a cache miss) will be higher.
If you simply want to avoid repeating step 1 (and maybe 2) again and again, parse the date once, then save the Date you get. You can then apply this date to your Calendar (with setDate()) before each add step again (or create a new GregorianCalendar, measure if it matters).