从AsyncStorage读取,解析数组,将字符串转换为Date对象

时间:2020-04-03 15:41:43

标签: javascript react-native parsing setstate asyncstorage

我正在尝试使用“提醒”键从异步存储中读取数组。

问题是JSON.parse无法将Array中的元素的'time'键转换为Date对象。

我需要使用setReminders()从存储中读取,解析并分配给提醒状态

// 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));
}

2 个答案:

答案 0 :(得分:1)

您可以使用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)
         }
      });
   });
}

答案 1 :(得分:1)

我在date添加了相同的问题。尝试使用moment而不是new Date()... 'npm安装时刻 import moment from "moment"; const time= '2020-04-03T15:17:07.554Z'; const todate= moment(time); 希望这会有所帮助。

相关问题