Convert Calendar to XMLGregorianCalendar with specific formatting - java

I am having some issues in converting a calendar object to an XMLGregorian calendar in the format of YYYY-MM-DD HH:mm:ss.
My current code is:
Calendar createDate = tRow.getBasic().getDateCreated(0).getSearchValue();
Date cDate = createDate.getTime();
GregorianCalendar c = new GregorianCalendar();
c.setTime(cDate);
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
which returns a date of 2013-01-03T11:50:00.000-05:00.
I would like it to read 2013-01-03 11:50:00.
I have checked a bunch of posts, which use DateFormat to parse a string representation of the date, however my dates are provided to me as a Calendar object, not a string.
I'd appreciate a nudge in the right direction to help me figure this one out.

An XMLGregorianCalendar has a specific W3C string representation that you cannot change.
However, you can format a Date with SimpleDateFormat.
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = dateFormat.format(cDate);
You can get a Date object from a XMLGregorianCalendar object as follows:
xmlCalendar.getGregorianCalendar().getDate()

DateFormat#format takes a Object parameter. From memory, it should accept a Calendar object, if not, it WILL accept a Date object, so you could use Calendar#getTime as a worse case scenario
You can use a instance of SimpleDateFormat to specify a custom formatting. This will ensure that the result is always the same for different systems

Have you seen this tutorial it may help?
http://www.vogella.com/articles/JavaDateTimeAPI/article.html
Speicifcally this code is a good example:
// Format the output with leading zeros for days and month
SimpleDateFormat date_format = new SimpleDateFormat("yyyyMMdd");
System.out.println(date_format.format(cal1.getTime()));

Related

Date value converted from Calendar outputs different format than String [duplicate]

I have the following scenario :
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.parse("31/05/2011"));
gives an output
Tue May 31 00:00:00 SGT 2011
but I want the output to be
31/05/2011
I need to use parse here because the dates need to be sorted as Dates and not as String.
Any ideas ??
How about:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")));
> 31/05/2011
You need to go through SimpleDateFormat.format in order to format the date as a string.
Here's an example that goes from String -> Date -> String.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("31/05/2011");
System.out.println(dateFormat.format(date)); // prints 31/05/2011
// ^^^^^^
Use the SimpleDateFormat.format
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String sDate= sdf.format(date);
You can use simple date format in Java using the code below
SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy");
Date newDate = new Date();
String expectedDate= simpledatafo.format(newDate);
It makes no sense, but:
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")))
SimpleDateFormat.parse() = // parse Date from String
SimpleDateFormat.format() = // format Date into String
If you want to simply output a date, just use the following:
System.out.printf("Date: %1$te/%1$tm/%1$tY at %1$tH:%1$tM:%1$tS%n", new Date());
As seen here. Or if you want to get the value into a String (for SQL building, for example) you can use:
String formattedDate = String.format("%1$te/%1$tm/%1$tY", new Date());
You can also customize your output by following the Java API on Date/Time conversions.
java.time
Here’s the modern answer.
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
DateTimeFormatter displayFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("zh-SG"));
String dateString = "31/05/2011";
LocalDate date = LocalDate.parse(dateString, sourceFormatter);
System.out.println(date.format(displayFormatter));
Output from this snippet is:
31/05/11
See if you can live with the 2-digit year. Or use FormatStyle.MEDIUM to obtain 2011年5月31日. I recommend you use Java’s built-in date and time formats when you can. It’s easier and lends itself very well to internationalization.
If you need the exact format you gave, just use the source formatter as display formatter too:
System.out.println(date.format(sourceFormatter));
31/05/2011
I recommend you don’t use SimpleDateFormat. It’s notoriously troublesome and long outdated. Instead I use java.time, the modern Java date and time API.
To obtain a specific format you need to format the parsed date back into a string. Netiher an old-fashioned Date nor a modern LocalDatecan have a format in it.
Link: Oracle tutorial: Date Time explaining how to use java.time.
You already has this (that's what you entered) parse will parse a date into a giving format and print the full date object (toString).
This will help you.
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
print (df.format(new Date());
I had something like this, my suggestion would be to use java for things like this, don't put in boilerplate code
This looks more compact. Finishes in a single line.
import org.apache.commons.lang3.time.DateFormatUtils;
System.out.println(DateFormatUtils.format(newDate, "yyyy-MM-dd HH:mm:ss"));

How do I format a java.sql.date into this format: "MM-dd-yyyy"?

I need to get a java.sql.date in the following format "MM-dd-yyyy", but I need it to stay a java.sql.date so I can put it into a table as date field. So, it cannot be a String after the formatting, it has to end up as a java.sql.date object.
This is what I have tried so far:
java.util.Date
today=new Date();
String date = formatter.format(today);
Date todaydate = formatter.parse(date);
java.sql.Date fromdate = new java.sql.Date(todaydate.getTime());
java.sql.Date todate=new java.sql.Date(todaydate.getTime());
String tempfromdate=formatter.format(fromdate);
String temptodate=formatter.format(todate);
java.sql.Date fromdate1=(java.sql.Date) formatter.parse(tempfromdate);
java.sql.Date todate1=(java.sql.Date) formatter.parse(temptodate);
You can do it the same way as a java.util.Date (since java.sql.Date is a sub-class of java.util.Date) with a SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat(
"MM-dd-yyyy");
int year = 2014;
int month = 10;
int day = 31;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1); // <-- months start
// at 0.
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
Output is the expected
10-31-2014
Use below code i have convert today date. learn from it and try with your code
Date today = new Date();
//If you print Date, you will get un formatted output
System.out.println("Today is : " + today);
//formatting date in Java using SimpleDateFormat
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy");
String date = DATE_FORMAT.format(today);
System.out.println("Today in MM-dd-yyyy format : " + date);
Date date1 = formatter.parse(date);
System.out.println(date1);
System.out.println(formatter.format(date1));
A simpler solution would be to just convert the date in the query to epoch before comparing.
SELECT date_column from YourTable where UNIX_TIMESTAMP(date_column) > ?;
Then, simply pass date.getTime() when binding value to ?.
NOTE: The UNIX_TIMESTAMP function is for MySQL. You'll find such functions for other databases too.
java.util.Date today=new Date();
java.sql.Date date=new java.sql.Date(today.getTime()); //your SQL date object
SimpleDateFormat simpDate = new SimpleDateFormat("MM-dd-yyyy");
System.out.println(simpDate.format(date)); //output String in MM-dd-yyyy
Note that it does not matter if your date is in format mm-dd-yyyy or any other format, when you compare date (java.sql.Date or java.util.Date) they will always be compared in form of the dates they represent. The format of date is just a way of setting or getting date in desired format.
The formatter.parse will only give you a java.util.Date not a java.sql.Date
once you have a java.util.Date you can convert it to a java.sql.Date by doing
java.sql.Date sqlDate = new java.sql.Date (normalDate.getTime ());
Also note that no dates have any built in format, it is in reality a class built on top of a number.
For anyone reading this in 2017 or later, the modern solution uses LocalDate from java.time, the modern Java date and time API, instead of java.sql.Date. The latter is long outdated.
Formatting your date
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-uuuu", Locale.US);
LocalDate fromDate = LocalDate.now(ZoneId.of("Asia/Kolkata"));
String tempFromDate = fromDate.format(formatter);
System.out.println(tempFromDate);
This prints something like
11-25-2017
Don’t confuse your date value with its textual representation
Neither a LocalDate nor a java.sql.Date object has any inherent format. So please try — and try hard if necessary — to keep the two concepts apart, the date on one side and its presentation to a user on the other.
It’s like int and all other data types. An int can have a value of 4284. You may format this into 4,284 or 4 284, 004284 or even into hex representation. This does in no way alter the int itself. In the same way, formatting your date does not affect your date object. So use the string for presenting to the user, and use LocalDate for storing into your database (a modern JDBC driver or other modern means of database access wil be happy to do that, for example through PreparedStatement.setObject()).
Use explicit time zone
Getting today’s date is a time zone sensitive operation since it is not the same date in all time zones of the world. I strongly recommend you make this fact explicit in the code. In my snippet I have used Asia/Kolkata time zone, please substitute your desired time zone. You may use ZoneId.systemDefault() for your JVM’s time zone setting, but please be aware that this setting may be changed under our feet by other parts of your program or other programs running in the same JVM, so this is fragile.

Getting formatted date in date format rather than String

I'm running the program written below, but instead of printing in mm/dd/yyyy hh:mm format it prints in the normal date format(ie. Day Date and time)
SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy hh:mm");
Date date = sdf.parse(sdf.format(Calendar.getInstance().getTime()));
The reason i'm doing this is because the existing method accepts parameters in Date format, so i need to send the above mentioned date object to it.
Please point out the mistake or suggest some other alternative.
Thanks
Date objects don't have a format. The Date class is a wrapper around a single long, the number of milliseconds since the epoch. You can't "format" a Date, only a String. Pass around a Date/Calendar internally, and format it whenever you need to display it, log it, or otherwise return it to the user.
Change the format to MM/dd/yyyy. Month is denoted by capital M.
Check below URL for valid formats
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Your formatter works quite fine (apart from the mm vs. MM bug). You get a formatted string from the date and then create a copy from your date by parsing the formatted string:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
Date now = Calendar.getInstance().getTime();
String formattedNow = sdf.format(now); // == "09/24/2013 01:59"
Date now2 = sdf.parse(formattedNow); // == now

Removing time from a Date object?

I want to remove time from Date object.
DateFormat df;
String date;
df = new SimpleDateFormat("dd/MM/yyyy");
d = eventList.get(0).getStartDate(); // I'm getting the date using this method
date = df.format(d); // Converting date in "dd/MM/yyyy" format
But when I'm converting this date (which is in String format) it is appending time also.
I don't want time at all. What I want is simply "21/03/2012".
You can remove the time part from java.util.Date by setting the hour, minute, second and millisecond values to zero.
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
public static Date removeTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
}
The quick answer is :
No, you are not allowed to do that. Because that is what Date use for.
From javadoc of Date :
The class Date represents a specific instant in time, with millisecond precision.
However, since this class is simply a data object. It dose not care about how we describe it.
When we see a date 2012/01/01 12:05:10.321, we can say it is 2012/01/01, this is what you need.
There are many ways to do this.
Example 1 : by manipulating string
Input string : 2012/01/20 12:05:10.321
Desired output string : 2012/01/20
Since the yyyy/MM/dd are exactly what we need, we can simply manipulate the string to get the result.
String input = "2012/01/20 12:05:10.321";
String output = input.substring(0, 10); // Output : 2012/01/20
Example 2 : by SimpleDateFormat
Input string : 2012/01/20 12:05:10.321
Desired output string : 01/20/2012
In this case we want a different format.
String input = "2012/01/20 12:05:10.321";
DateFormat inputFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = inputFormatter.parse(input);
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
String output = outputFormatter.format(date); // Output : 01/20/2012
For usage of SimpleDateFormat, check SimpleDateFormat JavaDoc.
Apache Commons DateUtils has a "truncate" method that I just used to do this and I think it will meet your needs. It's really easy to use:
DateUtils.truncate(dateYouWantToTruncate, Calendar.DAY_OF_MONTH);
DateUtils also has a host of other cool utilities like "isSameDay()" and the like. Check it out it! It might make things easier for you.
What about this:
Date today = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
today = sdf.parse(sdf.format(today));
What you want is impossible.
A Date object represents an "absolute" moment in time. You cannot "remove the time part" from it. When you print a Date object directly with System.out.println(date), it will always be formatted in a default format that includes the time. There is nothing you can do to change that.
Instead of somehow trying to use class Date for something that it was not designed for, you should look for another solution. For example, use SimpleDateFormat to format the date in whatever format you want.
The Java date and calendar APIs are unfortunately not the most well-designed classes of the standard Java API. There's a library called Joda-Time which has a much better and more powerful API.
Joda-Time has a number of special classes to support dates, times, periods, durations, etc. If you want to work with just a date without a time, then Joda-Time's LocalDate class would be what you'd use.
edit - note that my answer above is now more than 10 years old. If you are using a current version of Java (Java 8 or newer), then prefer to use the new standard date and time classes in package java.time. There are many classes available that represent just a date (day, month, year); a date and time; just a time; etc.
Date dateWithoutTime =
new Date(myDate.getYear(),myDate.getMonth(),myDate.getDate())
This is deprecated, but the fastest way to do it.
May be the below code may help people who are looking for zeroHour of the day :
Date todayDate = new Date();
GregorianCalendar todayDate_G = new GregorianCalendar();
gcd.setTime(currentDate);
int _Day = todayDate_GC.get(GregorianCalendar.DAY_OF_MONTH);
int _Month = todayDate_GC.get(GregorianCalendar.MONTH);
int _Year = todayDate_GC.get(GregorianCalendar.YEAR);
GregorianCalendar newDate = new GregorianCalendar(_Year,_Month,_Day,0,0,0);
zeroHourDate = newDate.getTime();
long zeroHourDateTime = newDate.getTimeInMillis();
Hope this will be helpful.
you could try something like this:
import java.text.*;
import java.util.*;
public class DtTime {
public static void main(String args[]) {
String s;
Format formatter;
Date date = new Date();
formatter = new SimpleDateFormat("dd/MM/yyyy");
s = formatter.format(date);
System.out.println(s);
}
}
This will give you output as21/03/2012
Or you could try this if you want the output as 21 Mar, 2012
import java.text.*;
import java.util.*;
public class DtTime {
public static void main(String args[]) {
Date date=new Date();
String df=DateFormat.getDateInstance().format(date);
System.out.println(df);
}
}
You can write that for example:
private Date TruncarFecha(Date fechaParametro) throws ParseException {
String fecha="";
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
fecha =outputFormatter.format(fechaParametro);
return outputFormatter.parse(fecha);
}
The correct class to use for a date without time of day is LocalDate. LocalDate is a part of java.time, the modern Java date and time API.
So the best thing you can do is if you can modify the getStartDate method you are using to return a LocalDate:
DateTimeFormatter dateFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("en-IE"));
LocalDate d = eventList.get(0).getStartDate(); // We’re now getting a LocalDate using this method
String dateString = d.format(dateFormatter);
System.out.println(dateString);
Example output:
21/03/2012
If you cannot change the getStartDate, you may still be able to add a new method returning the type that we want. However, if you cannot afford to do that just now, convert the old-fashioned Date that you get (I assume java.util.Date):
d = eventList.get(0).getStartDate(); // I'm getting the old-fashioned Date using this method
LocalDate dateWithoutTime = d.toInstant()
.atZone(ZoneId.of("Asia/Kolkata"))
.toLocalDate();
Please insert the time zone that was assumed for the Date. You may use ZoneId.systemDefault() for the JVM’s time zone setting, only this setting can be changed at any time from other parts of your program or other programs running in the same JVM.
The java.util.Date class was what we were all using when this question was asked 6 years ago (no, not all; I was, and we were many). java.time came out a couple of years later and has replaced the old Date, Calendar, SimpleDateFormat and DateFormat. Recognizing that they were poorly designed. Furthermore, a Date despite its name cannot represent a date. It’s a point in time. What the other answers do is they round down the time to the start of the day (“midnight”) in the JVM’s default time zone. It doesn’t remove the time of day, only sets it, typically to 00:00. Change your default time zone — as I said, even another program running in the same JVM may do that at any time without notice — and everything will break (often).
Link: Oracle tutorial: Date Time explaining how to use java.time.
A bit of a fudge but you could use java.sql.Date. This only stored the date part and zero based time (midnight)
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, 2011);
c.set(Calendar.MONTH, 11);
c.set(Calendar.DATE, 5);
java.sql.Date d = new java.sql.Date(c.getTimeInMillis());
System.out.println("date is " + d);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("formatted date is " + df.format(d));
gives
date is 2011-12-05
formatted date is 05/12/2011
Or it might be worth creating your own date object which just contains dates and not times. This could wrap java.util.Date and ignore the time parts of it.
java.util.Date represents a date/time down to milliseconds. You don't have an option but to include a time with it. You could try zeroing out the time, but then timezones and daylight savings will come into play--and that can screw things up down the line (e.g. 21/03/2012 0:00 GMT is 20/03/2012 PDT).
What you might want is a java.sql.Date to represent only the date portion (though internally it still uses ms).
String substring(int startIndex, int endIndex)
In other words you know your string will be 10 characers long so you would do:
FinalDate = date.substring(0,9);
Another way to work out here is to use java.sql.Date as sql Date doesn't have time associated with it, whereas java.util.Date always have a timestamp.
Whats catching point here is java.sql.Date extends java.util.Date, therefore java.util.Date variable can be a reference to java.sql.Date(without time) and to java.util.Date of course(with timestamp).
In addtition to what #jseals has already said. I think the org.apache.commons.lang.time.DateUtils class is probably what you should be looking at.
It's method : truncate(Date date,int field) worked very well for me.
JavaDocs : https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html#truncate(java.util.Date, int)
Since you needed to truncate all the time fields you can use :
DateUtils.truncate(new Date(),Calendar.DAY_OF_MONTH)
If you are using Java 8+, use java.time.LocalDate type instead.
LocalDate now = LocalDate.now();
System.out.println(now.toString());
The output:
2019-05-30
https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
You can also manually change the time part of date and format in "dd/mm/yyyy" pattern according to your requirement.
public static Date getZeroTimeDate(Date changeDate){
Date returnDate=new Date(changeDate.getTime()-(24*60*60*1000));
return returnDate;
}
If the return value is not working then check for the context parameter in web.xml.
eg.
<context-param>
<param-name>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</param-name>
<param-value>true</param-value>
</context-param>
Don't try to make it hard just follow a simple way
date is a string where your date is saved
String s2=date.substring(0,date.length()-11);
now print the value of s2.
it will reduce your string length and you will get only date part.
Can't believe no one offered this shitty answer with all the rest of them. It's been deprecated for decades.
#SuppressWarnings("deprecation")
...
Date hitDate = new Date();
hitDate.setHours(0);
hitDate.setMinutes(0);
hitDate.setSeconds(0);

problem converting calendar to java.util.Date

I need to create a java.util.Date object with an Australian timezone. this object is required for tag libraries used in downstream components (so I'm stuck with Date).
Here's what I have attempted:
TimeZone timeZone = TimeZone.getTimeZone("Australia/Sydney");
GregorianCalendar defaultDate = new GregorianCalendar(timeZone);
Date date = defaultDate.getTime();
However, "date" always returns the current local time (in my case, ET). What am I doing wrong here? Is it even possible to set a Date object with a different timezone?
Update:
Thanks for the responses! This works if I want to output the formatted date as a string, but not if I want to return a date object. Ex:
Date d = new Date();
DateFormat df = new SimpleDateFormat();
df.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
String formattedDate = df.format(d); // returns Sydney date/time
Date myDate = df.parse(formattedDate); // returns local time(ET)
I think I'm going to end up reworking our date taglib.
Is it even possible to set a Date object with a different timezone?
No, it's not possible. As its javadoc describes, all the java.util.Date contains is just the epoch time which is always the amount of seconds relative to 1 january 1970 UTC/GMT. The Date doesn't contain other information. To format it using a timezone, use SimpleDateFormat#setTimeZone()
getTime is an Unix time in seconds, it doesn't have the timezone, i.e. it's bound to UTC. You need to convert that time to the time zone you want e.b. by using DateFormat.
import java.util.*;
import java.text.*;
public class TzPrb {
public static void main(String[] args) {
Date d = new Date();
System.out.println(d);
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
System.out.println(df.format(d));
df.setTimeZone(TimeZone.getTimeZone("Europe/London"));
System.out.println(df.format(d));
}
}

Categories

Resources