Rectangle 27 1

I want to send the output in DD-MMM-YYYY format to the JSP page view.

Then you need to use a SimpleDateFormat to do so. Currently you're using the result of Date.toString(), and ignoring temp which should already have the right result.

However, you shouldn't need to parse the java.sql.Date at all - you can just pass it straight to DateFormat.format:

java.sql.Date date = /* get date from database */; 
// TODO: Specify time zone and locale
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = format.format(date);

Alternatively, I suspect that JSP already has a mechanism for allowing you to pass the date straight to the JSP itself, and specify the output format there... this is really a conversion to move as close to the presentation layer as possible.

@SaravananSivaji: Then you need to accept that a Date value doesn't have a format. It's just a point in time. There's no such thing as "a Date in DD-MMM-YY format". It's crucial that you understand the difference between a Date object and some string representation of it - you're currently saying there's a problem with a string representation, but that you won't be returning a string representation, only the Date value. Those two statements are contradictory.

my convertDate() is just an example sample tried separately. As you stated, I haven't parsed my java.sql.Date. I just assign as it is like object.setExpiryDate( resultSet.getDate("EXPIRY_DATE") ); Please see my @RestController spring code.

@SaravananSivaji: Right, so convertDate is irrelevant and you should remove it from the question. But fundamentally you've talked about your JSP converting the data to JSON, so that is a string representation. You need to find out exactly where that conversion from Date to String is being performed, and set the formatting there.

java.sql.Date (YYYY-MM-DD) to java.util.Date (DD-MMM-YYYY) conversion ...

java
Rectangle 27 1

The Answer by Elliott Frisch is correct. A comment asked is there is a better conversion recommended. There is. The better way also avoids the original problem, confusing java.util.Date with java.sql.Date.

The java.time framework built into Java 8 and later supplants the poorly-designed troublesome old java.util.Date/.Calendar classes and their kin. The new classes are inspired by the highly successful Joda-Time framework, similar in concept but re-architected. Defined by JSR 310. See the Oracle Tutorial. Extended by the ThreeTen-Extra project. Back-ported to Java 6 & 7 by the ThreeTen-Backport project, which is wrapped for use in Android by the ThreeTenABP project.

The LocalDate class represents a date-only value, without time-of-day and without time zone.

Your input string happens to comply with the ISO 8601 standard.

This standard is used by default in the java.time classes for parsing/generating date-time strings. So no need to specify a formatting pattern.

LocalDate localDate = LocalDate.parse( "2016-01-23" );

Eventually JDBC drivers will be updated to directly use java.time types. Until then when you need to fetch or send date-time values with a SQL database, convert between java.time and java.sql types. The old java.sql classes have new methods for such conversions. For LocalDate, use the java.sql.Date class (which pretends to be a date-only value).

java.sql.Date mySqlDate = java.sql.Date.valueOf( localDate );

and going the other direction

java.time.LocalDate localDate = mySqlDate.toLocalDate();

While converting String to Date got ambiguity between java.util.Date a...

java date ambiguity date-conversion
Rectangle 27 0

date = format1.parse(input);
String temp = format2.format(date);
System.out.println(temp)

Note that if you have JSTL you can format direcytly in the page:

<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<fmt:formatDate value="${bean.date}" pattern="dd-MMM-yy" />

Sorry for the belated reply. Yes, the above suggessions worked for me. :-) Thank you!!

java.sql.Date (YYYY-MM-DD) to java.util.Date (DD-MMM-YYYY) conversion ...

java
Rectangle 27 0

I want to send the output in DD-MMM-YYYY format to the JSP page view.

Then you need to use a SimpleDateFormat to do so. Currently you're using the result of Date.toString(), and ignoring temp which should already have the right result.

However, you shouldn't need to parse the java.sql.Date at all - you can just pass it straight to DateFormat.format:

java.sql.Date date = /* get date from database */; 
// TODO: Specify time zone and locale
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = format.format(date);

Alternatively, I suspect that JSP already has a mechanism for allowing you to pass the date straight to the JSP itself, and specify the output format there... this is really a conversion to move as close to the presentation layer as possible.

@SaravananSivaji: Then you need to accept that a Date value doesn't have a format. It's just a point in time. There's no such thing as "a Date in DD-MMM-YY format". It's crucial that you understand the difference between a Date object and some string representation of it - you're currently saying there's a problem with a string representation, but that you won't be returning a string representation, only the Date value. Those two statements are contradictory.

my convertDate() is just an example sample tried separately. As you stated, I haven't parsed my java.sql.Date. I just assign as it is like object.setExpiryDate( resultSet.getDate("EXPIRY_DATE") ); Please see my @RestController spring code.

@SaravananSivaji: Right, so convertDate is irrelevant and you should remove it from the question. But fundamentally you've talked about your JSP converting the data to JSON, so that is a string representation. You need to find out exactly where that conversion from Date to String is being performed, and set the formatting there.

java.sql.Date (YYYY-MM-DD) to java.util.Date (DD-MMM-YYYY) conversion ...

java
Rectangle 27 0

Dates in Java don't have a time zone. They're just a universal instant in time. If you want to display the date in a given time zone, then simply use a DateFormat initialized with this time zone:

DateFormat df = DateFormat.getInstance();
df.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("The date in the database, in the UTC time zone, is " 
                   + df.format(date));

You don't need to convert anything. The date format prints the appropriate values based on the universal instant it formats, and the time zone you tell it to use.

Similarly, if you want to know if the date is a monday or a tuesday, or if it's 1 o'clock or 2 o'clock, you need to first choose a time zone, convert it to Calendar, and ask the calendar for the information:

Calendar cal = Calendar.getInstance(someTimeZone);
cal.setTime(date);
System.out.println("The day for the date stored in the database, for the time zone "
                   + someTimeZone
                   + " is " + cal.get(Calendar.DATE));

>@JB Nizet thank you for your quick reply. Regarding using DateFormat... the df.format(dbDate) >does the time conversion again which is not required at this point. The "dbDate" stored in DB is actually a date stored after converting to utc. When i ran the code... following were the output... >dbDate --> 2012-07-30 13:45:00.0 >df.format(dbDate) --> 7/30/12 8:15 AM

>what i wanted to achieve is to attach a timezone information to dbDate (currently dbDate doesn't have the timezone attached to it, hence the dbDate gets default JVM's timezone). So that I can use the same date to convert again to some other timezone (say PST)

You haven't understood. Forget about all your conversions. There is no cenversion to make. A date represent a universal moment in time and doesn't have any time zone, and can't have one. It's only when you format the date that you need to choose with which timezone it must be formatted. But that doesn't change the date. Think of a date as "When Neill walked on the moon". If you format "When Neill walked on the moon", it can be midnight, or 1 o'clock, or 2 o'clock depending on which timezone you choose to format this moment. But they all represent the same moment, differently.

The reason for posting the question was.. I had stored 30Jul2012 10:30AM GMT on db... when i retrieved it on a server running on IST.. it started showing as 30Jul2012 10:30AM.. now when i took this date and converted to PST(GMT-8:00) it created ~12hr difference.. which is wrong, because it was understood to be in IST (i thought)... if the same date would have been read as GMT... the diff would have been 8hr.. I think i am able to convey it properly..

hibernate - Database datetime to java.util.Date conversion with timezo...

java hibernate date jdbc timezone
Rectangle 27 0

Here is one way of dealing with the problem ....

int flag=0;    
  if(exd.compareTo(sd)>0 )
       if(exd.compareTo(ed)<0){
             System.out.println(exd+" Lies between"+ sd +"and"+ ed);  
             flag=1;
       } 
  /*convert from newPattern to "yyyy-MM-dd"*/
  SimpleDateFormat formatterDB = new SimpleDateFormat(newPattern);
  Date temp = formatterDB.parse(nDate1);
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  String temp1 = formatter.format(temp);
  Date newDate1 = formatter.parse(temp1); 
  if(flag==1)
     if(exd.compareTo(newDate1)>0)
         if(exd.compareTo(newDate2)<0){
               /* your code to fetch other item from DB*/
         }

exd and newDate1 and newDate2 being in different formats are not getting compared and giving erroneous results. Anyway, good approach. Thanks!

I have added an approach for Date conversion method.

can you just check the example i posted.

Just To make it clear, nDate1 & nDate2 are in DB format (yyyy-MM-dd HH:mm:ss.SSS) and exd is in "yyyy-MM-dd" format ? And You need to convert from default DB format to "yyyy-MM-dd" format ? If so then use the above date conversion method .... it should work.

java.util.date Format Conversion - Stack Overflow

java date
Rectangle 27 0

If you're just comparing two dates, where one has precision down to time, you should just truncate the time so both just represent Date.

DateUtils.truncate(dateYouWantToTruncate, Calendar.Date);

Because your formatter is using ISO-8601 (year first, then month, then day), you can use the formatter you created to convert both dates to Strings and compare the strings.

formatter.format(sd).compareTo(formatter.format(newDate1));

You can also use the Calendar class. It's fairly verbose, but would work.

java.util.date Format Conversion - Stack Overflow

java date
Rectangle 27 0

import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import java.util.GregorianCalendar;
......
GregorianCalendar gcalendar = new GregorianCalendar();
gcalendar.setTime(yourDate);
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(gcalendar);

Code edited after the first comment of @f-puras, by cause i do a mistake.

Does not work the way you wrote it: GregorianCalendar.setTime() will not return anything.

xml - Simple conversion between java.util.Date and XMLGregorianCalenda...

java xml datetime jaxb gregorian-calendar
Rectangle 27 0

London time changed with Daylight Saving Time (DST) ending on 2013-10-27 when 2 AM became 1 AM (again).

unlike set(), add() forces an immediate recomputation of the calendar's milliseconds and all fields.

Furthermore, the documentation for java.util.GregorianCalendar on the add method notes that smaller units of time are not adjusted. The doc specifically notes that HOUR is a smaller field that DAY_OF_MONTH, so it is not adjusted. Meaning that you started with an hour of 23 so you'll end up with an hour of 23, with milliseconds-since-epoch recomputed as needed.

The behaviors you see for the set and add methods are both correct. Features, not bugs.

The bundled java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are notoriously troublesome, confusing, and tricky. They have flaws in both design and implementation.

I understand your interest in "to play with Java's built-in capabilities". While that interest is generally laudable, in this specific corner of Java, it is a waste of time. Even Sun and Oracle have given up on these classes. Java 8 brings a whole new java.time.* package, defined by JSR 310, inspired by Joda-Time, and supplanting the old bundled classes.

If you cannot yet move to Java 8, use Joda-Time. Joda-Time works in multiple versions of Java, and continues to work in Java 8 as it is actively maintained.

A Joda-Time DateTime actually knows its own time zone. In contrast, a java.util.Date has no time zone yet its toString method applies the JVM's default time zone which creates no end of confusion.

Note in this example that dateTime_Boston and dateTime_London have the same number of milliseconds-since-epoch.

Joda-Time by default uses standard ISO 8601 format for string output, like this 2014-02-13T10:32:28.131+05:30.

The + or - at the end marks a time zone offset from UTC/GMT. Do not read this as an operand in a formula. Read this as a label saying, for example, "India has a time zone offset of +05:30, so the date-time displayed is five and a half hours ahead of UTC/GMT".

The Z at the end is pronounced "Zulu" and is shorthand for +00:00. That means UTC/GMT time zone, that is, no time zone offset.

// Specify a time zone rather than rely on default.
DateTimeZone timeZone_Boston = DateTimeZone.forID( "America/New_York" );
DateTimeZone timeZone_London = DateTimeZone.forID( "Europe/London" );

DateTime dateTime_Boston = new DateTime( 2013, 10, 27, 22, 51, 12, timeZone_Boston );
DateTime dateTime_London = dateTime_Boston.toDateTime( timeZone_London ); 
DateTime earlier_London = dateTime_London.minusDays( 2 ); // Use '2' to get us before DST change.
DateTime earlier_UtcGmt = earlier_London.toDateTime( DateTimeZone.UTC );
System.out.println( "dateTime_Boston " + dateTime_Boston );
System.out.println( "dateTime_London " + dateTime_London );
System.out.println( "earlier_London " + earlier_London );
System.out.println( "earlier_UtcGmt " + earlier_UtcGmt );
dateTime_Boston 2013-10-27T22:51:12.000-04:00
dateTime_London 2013-10-28T02:51:12.000Z
earlier_London 2013-10-26T02:51:12.000+01:00
earlier_UtcGmt 2013-10-26T01:51:12.000Z

Thank you. Your examples are using the Joda time library, right? I am pretty sure but just making sure.

@peter.petrov Yep, Joda-Time 2.3, that's what it says under "Example Code" heading.

java.util.Date - Test Conversion US <-> UK - Stack Overflow

java date datetime timezone date-conversion
Rectangle 27 0

Struts recognizes certain object types as listed in the Built in Type Conversion Support section for the documentation and as explained in the linked answer by Andrea.

If you're wondering why your Date object render as m/d/yy format even though you are using an <s:property> tag instead of an <s:date> tag, it's because Date is one of the types that Struts2 has built-in conversion for.

So instead of calling the default toString() method of the Date object, Struts2 will use the built-in type converters to display the String.

In the com.opensymphony.xwork2.conversion.impl.StringConverter class, Struts2 will attempt to convert the Date object to a String in a meaningful way using the default format for the Locale as mentioned by Andrea and the documentation.

+1 for remarking the point with a detailed explanation

One more related question : Does <s:date> tag is thready safe? By looking at StringConverter code it looks like thread safe. Few days back I was using <s:text name='date'> with date = {0,date,yyyy-MM-dd} in package properties and I have observed that results were messing up which gave me an impression that <s:text> tag is not thread safe. Is it correct observation? For detail question please check : stackoverflow.com/questions/21574731/

Yes I also think so but while using <s:text> tag I have observed that responses for parallel requests were messing up.

jsp - How come struts property tag converts java.util.Date in m/d/yy f...

jsp struts2
Rectangle 27 0

For date formatting and styling,After you fetch the date from the database and before you print or send them you can format them in your preferred style and remove the .0 (dot zero) from the string.

mysql - Strange behavior of Struts2 Type conversion for java.util.Date...

java mysql hibernate date struts2
Rectangle 27 0

date = format1.parse(input);
String temp = format2.format(date);
System.out.println(temp)

Note that if you have JSTL you can format direcytly in the page:

<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<fmt:formatDate value="${bean.date}" pattern="dd-MMM-yy" />

Sorry for the belated reply. Yes, the above suggessions worked for me. :-) Thank you!!

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

java.sql.Date (YYYY-MM-DD) to java.util.Date (DD-MMM-YYYY) conversion ...

java
Rectangle 27 0

Please change small "mm" month to capital "MM" it will work.for reference below is the sample code.

**Date myDate = new Date();
    SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy");

    String strDate = sm.format(myDate);

    Date dt = sm.parse(strDate);
    System.out.println(strDate);**

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy - Stack Over...

java date date-format
Rectangle 27 0

java.util.Date dt = xmlGregorianCalendarInstance.toGregorianCalendar().getTime();

Thanks... I was looking for a way to convert XMLGregorianCalendar to time in millis.

xml - Simple conversion between java.util.Date and XMLGregorianCalenda...

java xml datetime jaxb gregorian-calendar
Rectangle 27 0

I have had problems with @JodaStephen's implementation on JBoss EAP 6. So, I rewrote the conversion following Oracle's Java Tutorial in http://docs.oracle.com/javase/tutorial/datetime/iso/legacy.html.

Date input = new Date();
    GregorianCalendar gregorianCalendar = (GregorianCalendar) Calendar.getInstance();
    gregorianCalendar.setTime(input);
    ZonedDateTime zonedDateTime = gregorianCalendar.toZonedDateTime();
    zonedDateTime.toLocalDate();

datetime - Convert java.util.Date to java.time.LocalDate - Stack Overf...

java datetime java-8 java-time
Rectangle 27 0

Why not use an external binding file to tell XJC to generate java.util.Date fields instead of XMLGregorianCalendar?

No problem. JAXB can handle the java.util.Date type, you just need to generate it in your model. Which can be tricky.

I added jaxb bindings but right below xs:schema and I get the following error: com.sun.istack.SAXParseException2: compiler was unable to honor this globalBindings customization. It is attached to a wrong place, or its inconsistent with other bindings. at com.sun.tools.xjc.ErrorReceiver.error(ErrorReceiver.java:86) at ..

@pritam - Here is another example that may help: blog.bdoughan.com/2011/08/xml-schema-to-java-generating.html. It may be worth staring a new question for the issue you are seeing.

xml - Simple conversion between java.util.Date and XMLGregorianCalenda...

java xml datetime jaxb gregorian-calendar
Rectangle 27 0

Actually there is. There is a static method valueOf in the java.sql.Date object which does exactly that. So we have

java.util.Date date = java.sql.Date.valueOf(localDate);

and that's it. No explicit setting of time zones because the local time zone is taken implicitly.

The provided LocalDate is interpreted as the local date in the local time zone.

java.sql.Date
java.util.Date

And for the reverse operation there is a toLocalDate method in the java.sql.Date class. So we have:

LocalDate ld = new java.sql.Date(date.getTime()).toLocalDate();

The original question Date is also in system timezone. Using java.sql.Date for a actual date is not that far fetched, IMHO.

This answer can NOT be recommended because a) it lacks support for different timezones and b) mix up two different types where the inheritance relationship only denotes an implementation-driven dependency. The type java.sql.Date should only be applied in context of JDBC. Best answer see that from @Basil Bourque

As Hochschild said, the class doc tells us to ignore the inheritance subclass relationship between java.util.Date & java.sql.Date, tells us to not do what this Answer does. Furthermore that valueOf method does not skirt the issue of time zone, it merely hides the issue while silently applying the JVMs current default zone in setting the time-of-day to midnight. So the statement No time zones, no complications is incorrect: There are time zones involved, and there are complications, you've just chosen to ignore them. The java.time classes were invented for a reason; use them.

As the author of the java.time.* libraries I am saddened that over 40 people have seen fit to upvote this. The correct answer is here and Basil's below. Using java.sql.Date is a horrible hack as expressed in other comments and this approach hides the time-zone conversion, which is a Bad Thing. It has also been known for years that java.sql.Date should never have extended java.util.Date. Finally, when using modules in Java 9, the java.sql classes will be a separate dependency, so using this hack will have consequences.

LocalDate to java.util.Date and vice versa simplest conversion? - Stac...

java date java-8 java-time
Rectangle 27 0

I've been toying yesterday with Nashorn in pure javascript to generate self signed certificates. In one of the steps, the error message cannot cast to java.util.Date occurred.

The only way to fix it in my js file was to specifically request a java.util.Date object, like this:

certGen.setNotBefore(new java.util.Date(System.currentTimeMillis() - mdelta));

If you do not do so, you'll get the following message:

Exception in thread "main" java.lang.ClassCastException: Cannot cast jdk.nashorn.internal.objects.NativeDate to java.util.Date

So I suggest the following code for you:

Object js = engine.eval("new java.util.Date();");

javascript - Nashorn NativeDate conversion to java.util.Date - Stack O...

java javascript date nashorn
Rectangle 27 0

Cast returned JavaScript object on jdk.nashorn.api.scripting.ScriptObjectMirror, then you will be able to access its properties in a "map-like" manner.

ScriptObjectMirror jsDate = (ScriptObjectMirror) engine.eval("new Date();")
long timestampLocalTime = (Long) jsDate.callMember("getTime"); 
// yes, js date returns timestamp in local time so you need to adjust it... ;)
int timezoneOffsetMinutes = (Integer) jsDate.callMember("getTimezoneOffset");
// java.util.Date construcctor utilizes UTC timestamp
Date jDate = new Date(timestampLocalTime + timezoneOffsetMinutes * 60 * 1000);

However if you are about to use some "JavaScript class" frequently on the Java side - you may find it useful to define "overlay" interface to access javascript object's methods in more convenient way. See the following example:

public interface JsDateWrap {
    long getTime();
    int getTimezoneOffset();
    // ...
}

Object jso = engine.eval("new Date();");
JsDateWrap jsDate = ((Invocable) engine).getInterface(jso, JsDateWrapper.class);
Date jDate = new Date(jsDate.getTime() + jsDate.getTimezoneOffset() * 60 * 1000);

javascript - Nashorn NativeDate conversion to java.util.Date - Stack O...

java javascript date nashorn
Rectangle 27 0

The class java.sql.Date is designed to carry only a date without time, so the conversion result you see is correct for this type. You need to use a java.sql.Timestamp to get a full date with time.

java.util.Date newDate = result.getTimestamp("VALUEDATE");

this should work, but since java.sql.Timestamp also derives from java.util.Date you could as well just use the Timestamp instance.

jdbc - Converting java.sql.Date to java.util.Date - Stack Overflow

java jdbc