1

I'm working with date-fns and react-datepicker. I am having a problem with saving the date to my SQL Server Db as it is always a day behind. I assume it is saving the UTC timestamps, but I want to display the day in my locale timezone which is NZ time. I have tried passed the locales enNZ to the datepicker and date-fns format() and parseISO() but its still not working. The datepicker selects the correct date but its saving the previous date when i create the record to my Db.

Any help would be appreciated.

screenshot

//Table Component

if (col === 'dateSold') {
    return (<td key={col}>{format(new Date(item[col]), 'dd/MM/yyyy', nz)}</td>)
}

//i have also tried this
format(parseISO(item[col]).getTime(), 'dd/MM/yyyy', nz)


//Sales Component

import nz from 'date-fns/locale/en-NZ';

export default class Sales extends Component {
    constructor(props) {
        super(props);
        this.state = {
                dateSold: this.props.data ? parseISO((this.props.data.dateSold), 'dd/MM/yyyy', nz) : new Date()
            }
    }   
        
    handleDate = (date) => {
        this.setState({ dateSold: date })
        console.log(this.state.dateSold);
    }       
        
    render() {
        return (
            <>  
            <DatePicker
                locale={nz}
                selected={this.state.dateSold}
                onChange={this.handleDate}
                dateFormat="dd/MM/yyyy"
                name="dateSold"
            />
            </>
        )
    }
Firestarter
  • 77
  • 1
  • 10

1 Answers1

0

Looks like there's registerLocale() to do. Already Answered here

Also, your application may not require it, but I'd really prefer saving UTC timestamp in database instead of a localized one.

Alan P.
  • 2,898
  • 6
  • 28
  • 52
  • 1
    Hi there. I've tried registerLocale() but i'm still having the same problem. It's storing the date to the previous day even after selecting the correct date on datepicker – Firestarter Nov 21 '20 at 23:01