How to set format of current date time to differen

2020-08-04 04:37发布

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;
    }

3条回答
Viruses.
2楼-- · 2020-08-04 04:43

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}"/>
查看更多
放我归山
3楼-- · 2020-08-04 04:46

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.)

查看更多
来,给爷笑一个
4楼-- · 2020-08-04 04:56

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);
查看更多
登录 后发表回答