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");
Related
I've seen the following code and I'm confused about the use of Regex here. The requirement of this checkDateSanity method is:
The DATE format is dd.MM.yyyy. (WARNING: the DATE must exist!!)
private boolean checkDateSanity(String dateString) {
if (Pattern.matches("[0-3][0-9].[0-1][0-9].[0-9]{4}", dateString)) {
try {
DateFormat df = new SimpleDateFormat(DATE_FORMAT);
df.setLenient(false);
df.parse(dateString);
return true;
} catch (ParseException e) {
return false;
}
}
return false;
}
I've read this post on a similar topic How to sanity check a date in Java, where the answer simply uses
try {
DateFormat df = new SimpleDateFormat(DATE_FORMAT);
df.setLenient(false);
df.parse(dateString);
return true;
} catch (ParseException e) {
return false;
}
I did some random tests and the Regex doesn't make any difference with or without it. Is there any deeper reason to have the Regex check here? Like to reduce the computation cost? If that's the case, is it really worth it?
Define 'valid'.
The regex, for example, allows For the 39th day of the 19th month, as well as the 0th day of the 0th month: 39-19-0000 is a valid date according to it, but 1-1-2020 is not (only 01-01-2020 would be).
The SDF is old API that you shouldn't use (use java.time), but as far as this code goes, lenience is turned off, so it does not accept 39-19-0000, though it would accept 1-1-2020.
Combining the two gets you the strictest take, but it sure feels convoluted. Is there a particular heinous issue with accepting 1-1-2020?
But note this gigantic problem: Year confusion. 1-1-99 WILL parse with a .setLenient(false) SDF with pattern dd.MM.yyyy, and is interpreted as jan 1st during the year 99, sometime during the days of the roman empire (not like the prince song).
For that purpose alone, that regex is quite useful; you can use the regexp to error out if a 2-digit year is passed, as SDF can't reject that kind of input.
Thus, the real advice!
Those old date apis are so incredibly bad. They suck. Do not use them. Update your IDE, mark down SimpleDateFormat as illegal. Here is the java time package, doing precisely what you want. Note that SDF returns a java.util.Date which is a lying liar who lies: That represent an instant in time and has no business representing dates. It really doesn't - that's why all the various .getYear() etc methods are deprecated.
LocalDate x = LocalDate.parse("01.01.1999", DateTimeFormatter.ofPattern("dd.MM.yyyy"));
System.out.println(x);
> 1999-01-01
// Awesome. It's an actual _DATE_ and not a timestamp where timezones
// can mess everything up.
LocalDate x = LocalDate.parse("01.01.99", DateTimeFormatter.ofPattern("dd.MM.yyyy"));
> Exception in thread "main" java.time.format.DateTimeParseException: Text '01.01.1999' could not be parsed
// perfect. it crashes, as it should.
LocalDate x = LocalDate.parse("1.1.1999", DateTimeFormatter.ofPattern("dd.MM.yyyy"));
> Exception in thread "main" java.time.format.DateTimeParseException: Text '01.01.1999' could not be parsed
// if you want `1.1.1999` to crash, well, you can.
LocalDate x = LocalDate.parse("1.1.1999", DateTimeFormatter.ofPattern("d.M.yyyy"));
System.out.println(x);
> 1999-01-01
// but you don't have to. with just `d`, 1 parses as 1, so does 01.
You can go with yy too, which FORCES that you only use 2 digits; they are all interpreted as 20xx. (1.1.99 is 2099-01-01).
Using the following block of code I am trying to convert a UTC JODA time to a specified timezone using a string vale, e.g "Asia/Tokyo"
public void handleTimezoneConversion(TimesheetEntry timesheetEntry, String timezone) {
System.out.println("TO :"+timezone);
System.out.println(timesheetEntry.getStartDateTime());
LocalDateTime startDateTime = timesheetEntry.getStartDateTime();
startDateTime.toDateTime(DateTimeZone.forID(timezone));
timesheetEntry.setStartDateTime(startDateTime);
System.out.println(timesheetEntry.getStartDateTime());
LocalDateTime endDateTime = timesheetEntry.getEndDateTime();
endDateTime.toDateTime(DateTimeZone.forID(timezone));
timesheetEntry.setEndDateTime(endDateTime);
}
When i run it the time stays the same evn though there should be a noticeable difference.
Where am I going wrong, are my methods off course completely?
LocalDateTime's toDateTime() method returns a DateTime. In your code, you're calling toDateTime() but discarding the return value. Instead, you'll want to do something like this:
DateTime newDateTime = startDateTime.toDateTime(DateTimeZone.forID(timezone));
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.
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).