简体   繁体   English

从 AsyncStorage 读取,解析数组,将字符串转换为日期 object

[英]Read from AsyncStorage, Parse Array, Convert String to Date object

I'm trying to read array from Async storage with "reminders" key.我正在尝试使用“提醒”键从异步存储中读取数组。

Problem is JSON.parse cannot convert 'time' key of element in Array to Date object.问题是 JSON.parse 无法将数组中元素的“时间”键转换为日期 object。

I need to read from storage, parse and assign to reminders state using setReminders()我需要使用 setReminders() 从存储中读取、解析并分配给提醒 state

// EXAMPLE DATA IN ASYNC STORAGE
[{day: 'Monday', time: '2020-04-03T15:17:07.554Z', status: false},
{day: 'Friday', time: '2020-04-03T15:17:07.951Z', status: true},]


// LOAD REMINDERS
  useEffect(readReminders, []);

  function readReminders() {
   AsyncStorage.getItem('reminders').then(value =>setReminders(value));
}

You can parse Date from string using Date.parse(string) or new Date(string) like:您可以使用Date.parse(string)new Date(string)从字符串中解析日期,例如:

function readReminders() {
   AsyncStorage.getItem('reminders').then(values => {
      const reminders = values.map(item => {
         return {
           ...item,
           time: new Date(item.time)
         }
      });
   });
}

I have add the same issue with the date.我在日期上添加了同样的问题。 try using moment instead of new Date()... 'npm install moment import moment from "moment"; const time= '2020-04-03T15:17:07.554Z'; const todate= moment(time);尝试使用 moment 而不是 new Date()... 'npm install moment import moment from "moment"; const time= '2020-04-03T15:17:07.554Z'; const todate= moment(time); import moment from "moment"; const time= '2020-04-03T15:17:07.554Z'; const todate= moment(time); Hope this will help.希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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