简体   繁体   中英

Create new column with reformated date

I have a column named 'date' formatted as date-type with values like 2007-08-24T00:00:00Z

I would like to populate a new column called date2 with a reformatted string like August 24th, 2007

Below is my attempt at this. What am I missing?

UPDATE myTable SET date2 = date_part('Mon DD, YYYY',date);

As noted in the comments, if your column is one of the built-in date/time types - date , timestamp , etc - then it is not stored in the database with any particular string format, but as abstract data. This is the only way you should ever store dates in the DB, as it allows you to perform a whole range of operations directly on the data.

To format such a value, you apply an appropriate formatting when you select the data . I would strongly recommend against storing this formatted string anywhere - it adds no value to your database, since any format can be calculated at any time, but does mean you have duplicated data to manage in future.

The formatting functions take a slightly unusual specifier format; in your case, I believe you want 'FMMonth Dth, YYYY' :

 SELECT
    to_char("date", 'FMMonth Dth, YYYY') as formatted_date
 FROM
    my_table;

As an alternative trick, if you happen to be using PHP, you can select the date out as a Unix timestamp, and then use PHP functions to format that:

 SELECT
    extract(epoch from "date") as unix_date
 FROM
    my_table;

this does the trick

UPDATE myTable SET date2 = to_char(date,'Month DD, YYYY')

如果由于某种原因而对调用日期格式函数感到厌烦,则可以将extract()to_char()放入函数中,或在表上创建适当的视图。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM