简体   繁体   中英

PostgreSQL Date is one day off with my Query

I am working on a React Native App with Expo that is connected to a PostgresDB.

I have a query that loads some Data in between two dates it looks like this:

db.query(
      `SELECT activitydate, phaseid, time, userid, remark, zkub, status, hours_status.color status_color, comment, project.name project_name
      FROM hours 
      LEFT JOIN phase ON phase.id = hours.phaseid
      LEFT JOIN project ON project.id = phase.projectid 
      LEFT JOIN hours_status ON hours_status.statusid = hours.status
      WHERE activitydate >= '${startDate}' AND activityDate <= '${endDate}'
      AND userid = '${userid}' ORDER BY activitydate`

... startDate is 2019-08-01 and endDate is 2019-08-31 in this example ! 

It does give me back the data I need(example):

{"activitydate":"2019-07-31T22:00:00.000Z","phaseid":766x7,"time":180,"userid":1xx,"remark":"I did this and that","zkub":" ","status":0,"status_color":"000000","comment":"","project_name":"coolProject"}
... of course this is 1 Element from the Array ! 

Now the problem is that the activitydate should be : "2019-08-01" but it is "2019-07-31" even though it is safed correctly inside the db with the correct activitydate.

Its not only wrong when I get the data in the browser with a localhost/api/... but it's also displayed wrong inside my app.

I think it might have something to do with the Timestamp that is set? it is set to T22:00:00.000Z as you can see. I dont know which date the browser or nodejs(express) might be using but it puts the results 1 day behind.

If you want to get records between two dates then use

WHERE activitydate between `${startDate}` and `${endDate}`

also make sure you are passing your date in right format like YYYY-MM-DD

using moment we can format our date in required format

 moment(our_date).format('YYYY-MM-DD')  // npm install moment --save

So, when you get your result then pass your result activitydate to moment it will return date in YYYY-MM-DD format

Try to use format(datee,'dd - MM - yyyy') function like

SELECT DATE_FORMAT(activitydate, "%Y-%m-%d") // try instead of activitydate 

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