How to set format of current date time to different format?

孤街醉人 提交于 2020-01-13 07:13:26

问题


I use the following code to retrieve the current date and time, then add it to table using following method.

 Change 2013-07-29 23:20:34.0 to 29th July 2013, 11:20 PM

DateTime

 public Date getCurrentDateTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        System.out.println("current:" + dateFormat.format(date));
        return date;
    }

Hibernate

@Temporal(javax.persistence.TemporalType.TIMESTAMP)
    public Date getCurrentDateTime() {
        return date;
    }

回答1:


To change the day to ordinal number you need to use the following suffix. have a look at this link as well

DD +     TH = DDTH  result >>>> 4TH

OR to spell the number add SP to the format

DD + SPTH = DDSPTH   result >>> FOURTH

Also use the fmt library to format the date on jsp pages

 <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

 <fmt:formatDate type="both" dateStyle="long" timeStyle="short" 
      value="${date}"/>



回答2:


A Date object doesn't have a format. (Neither java.sql.Date nor java.util.Date.) The database will just store it in the table in whatever native representation it chooses (almost certainly not text) and when you retrieve the data it's up to you to format it how you wish.

To change the format used by System.out.println, just change the pattern you're passing to the SimpleDateFormat constructor - see the documentation for details. Note that you should consider which time zone and Locale you're interested in, too - for example, month names won't be the same between different locales, and different locales also have different expected formats. (Even within the same language, there are different conventions.)

You'll find the "th" of "29th" hard to handle with SimpleDateFormat - I don't believe it supports ordinals. This question may help you though. (It's going to be ugly code, mind you - I would suggest changing the format to remove the ordinal if you possibly can.)




回答3:


Something similar to this ??

for hibernate

SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String dateBufferString = format.format(date);
Date dateBuffer;
try {

dateBuffer = format.parse(dateBufferString);
System.out.println("Database Date Format :" + date);
System.out.println("(dd-MM-yyyy) date: " + format.format(date));
System.out.println("dateBufferSTring " + dateBufferString);
System.out.println("dateBuffer: " + dateBuffer);


来源:https://stackoverflow.com/questions/17939329/how-to-set-format-of-current-date-time-to-different-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!