我解释了我今天的问题
在下面的代码中,我发布对象
我的问题是,有没有可能发布这篇文章的发布时间?
postbackend = () =>{
const config = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({...this.state, items:this.props.items}),
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
if (res.error) {
alert(res.error);
} else {
alert(`ajouté avec l'ID ${res}!`);
}
}).catch(e => {
console.error(e);
}).finally(()=>this.setState({ redirect: true }));
}我只是想恢复这篇文章发布的时间,你有办法解决这个问题吗?效果
发布于 2020-02-18 18:46:39
body: JSON.stringify({...this.state, created: new Date().toISOString(), items:this.props.items})这会将时间戳添加到POST正文中。
您应该考虑到这样一个事实:这被认为是一个糟糕的做法。因为用户在其计算机上的时间可能不同。这可能会导致不一致。解决这个问题的最好方法是在服务器上设置日期/时间。
发布于 2020-02-18 18:45:34
postbackend = () => {
startDate = new Date(); // add this date
const config = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
...this.state,
items: this.props.items
}),
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
if (res.error) {
alert(res.error);
} else {
alert(`ajouté avec l'ID ${res}!`);
}
}).catch(e => {
console.error(e);
}).finally(() => this.setState({
redirect: true
}));
return startDate; // return it
}在此之后,您将获得每个postbackend的日期
const date1 = postbackend();
const date2 = postbackend();
const date3 = postbackend();您可以将它们保存在列表中
const dates = [];
dates.push(postbackend());将它们持久化到数据库中,等等
发布于 2020-02-18 18:50:30
如果你想把时间和请求一起发送,你只需要把它添加到请求的正文中,如下所示:
JSON.stringify({...this.state, items:this.props.items, postTime: Date.now()})Date.now()返回1970年1月1日以来的时间(以毫秒为单位)。https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date
如果要将其格式化为字符串,可以执行以下操作:
const dateNow = Date.now(); // Date in milliseconds since 1st January 1970
const date = new Date(dateNow); //Creates a date object from the milliseconds
console.log(dateNow);
console.log(date);
console.log(date.toLocaleString('en-GB', { timeZone: 'UTC' }));
我希望这能帮到你。
https://stackoverflow.com/questions/60278939
复制相似问题