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.
I need to read from storage, parse and assign to reminders state using 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));
}
You can parse Date from string using Date.parse(string) or new Date(string) like:
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);
Hope this will help.
Related
Problem
I have below function that formats date string.
import { format, parseISO } from "date-fns";
export function convertDate(myDate, displayFormat) {
return format(new Date(parseISO(myDate)), displayFormat);
}
I have articles that has content such as
title: 'My title'
date: '2022-01-04'
I call the convertDate function using below:
if (articles) {
for (let i = 0; i < articles.length; i++) {
const year = convertDate(articles[i].date, "y");
years.push(year);
}
uniqueYear = [...new Set(years)];
}
My timezone is CEST.
Error
I am getting error:
Expected result:
I can call the function by using {convertDate(article.date, "PPP")} which also works.
Please help!
Running the following minimal example at runkit.com returns "2022", it doesn't throw the error described in the OP:
var dateFns = require("date-fns")
function convertDate(myDate, displayFormat) {
return dateFns.format(new Date(dateFns.parseISO(myDate)), displayFormat);
}
let articles = [{
title: 'My title',
date: '2022-01-04'
}];
convertDate(articles[0].date, "y"); // "2022"
So the error is elsewhere.
Also, the use of new Date is redundant:
dateFns.format(dateFns.parseISO(myDate), displayFormat)
is sufficient and more robust.
As suggested elsewhere, getting the year from the timestamp can be done using string manipulation, no need for casting to a Date. To get the years:
let articles = [{title: 'title 0', date: '2022-01-04'},
{title: 'title 1', date: '2020-01-04'}];
let years = articles.map(o => o.date.substring(0,4));
console.log(years);
If you need it as a Date for other things (e.g. formatted month name), cast it to a Date once and reuse it.
I am currently creating an animal shelter web app using mern and i have trouble grouping data by date month. so i have this schema for the rescued date:
const animalSchema = new mongoose.Schema({
date_rescued: {
type: Date,
default: Date.now,
},
})
module.exports = mongoose.model('Animal', animalSchema);
And here on my animal controller backend this is my query for fetching the datas:
exports.getRescuedChart = async(req,res,next) => {
const rescuedanimals = await Animal.find({}).select(['date_rescued']);
res.status(200).json({
success:true,
rescuedanimals,
})
}
the data that this function is returning to the state is this:
what i want to have is group them by data and count how many object has the same date.
rescuedanimals =[
{
date_rescued: "April",
animal_count: 8
}
]
so yeah i just learn how to do it myself so here's what i did.
first is that i installed dataeformat library: 'npm install dateformat'
i import it on my project: import dateFormat from 'dateformat';
what i did first is to change the date format and reduce duplicate dates.
const groups = rescuedanimals.reduce(
(groups, rescued_animal) => {
const date = dateFormat(rescued_animal.date_rescued[0], "mmmm")
if (!groups[date]) {
groups[date]=[]
}
groups[date].push(rescued_animal);
return groups;
}, {}
)
after that i created a new function to put this on an arraay and also to get the legnth of the objects that are in that date.
const groupArrays = Object.keys(groups).map((date) => {
return {
date,
games: groups[date].length
};
});
thanks to Austin Greco: https://stackoverflow.com/a/46802505/12398637
I use WeatherAPI's service, which returns the weather forecast given the city name
The URL looks like this https://api.weatherapi.com/v1/forecast.json?key=[API_KEY]&q=tokyo&aqi=no
After trying to paste that URL into my browser and pasting the result into a JSON beautifier, here's the result
Here's the weird part. I tried using axios to fetch the information from my app and printing it out, this is what it gave me
It was unable to fetch forecastday and instead gave me a [Object], which didn't make any sense to me since it worked just fine on my browser
Here's my code (sorry for the spaghetti formatting)
https://pastebin.com/9eJQy5Bf
I tried reinstalling the library, using proxies but the result remained the same.
forecast.forecastday is an object array, to access a property from a particular object, you have to specify the index of the object in the array.
For example if you want the date property of the first object.
const data = {
forecast: {
forecastday: [{
date: "2022-04-03"
}]
}
}
const date = data.forecast.forecastday[0].date; // index [0] = first element
console.log(date);
If you would have multiple days, you could loop over them or use a function like map() to get the specific items.
const data = {
forecast: {
forecastday: [{
date: "2022-04-03",
date_epoch: 123456789
},
{
date: "2022-04-04",
date_epoch: 123456789
}
]
}
}
const dates = data.forecast.forecastday.map(({ date }) => {
return { date }
});
console.log(dates);
I'm a bit new to Vue and was wondering how to get the the past month date: I have this code:
import SomeTable from "./table/SomeTable";
export default {
name: "Cabinets",
components: {SomeTable},
data() {
return {
defaultColumns: [
'id',
'serialNumber'
],
defaultStartDate: new Date(),
defaultEndDate: new Date('2019-10-07')
}
},
props: {
startDate: {type: Date, required: false},
endDate: {type: Date, required: false},
}
}
</script>
And then I put defaultStartDate and defaultEndDate in the SomeTable element as follows:
<some-table :start-date="defaultStartDate" :end-date="defaultEndDate" :default-columns="defaultColumns"></some-table>
Which then returns the correct startDate of today and also the set one. But when i try for instance to do something like this:
defaultEndDate: new Date().getFullYear() + '-' + new Date().getMonth() + '-' + new Date().getDate()
My local environment turns blank and get all sorts of errors. I think this is due to the fact I can't use Javascript in that place in Vue? But again I'm really not yet sure how Vue works and couldn't find much on it by googling. So how could I do this using Javascript or maybe even if Vue has a neat trick for it?
EDIT:
the errors i'm getting are of the form:
Error in data(): "TypeError: Date().getFullYear is not a function"
But then with all the javascript functions i used inside Vue. And also
Invalid prop: type check failed for prop "endDate". Expected Date, got String with value "2019-9-5".
In your codes, endDate: {type: Date, required: false}, means endDate should be in Date type.
So you need to convert calculated value into Date like below:
defaultEndDate: new Date(`${(new Date()).getFullYear()}-${(new Date()).getMonth()}-${(new Date()).getDate()}`)
EDIT:
And you need to think of the month is January(0). By using the above method, you will get error when it is on January.
I think It could be better to use computed value like below;
computed: {
defaultEndDate() {
const now = new Date();
now.setMonth(now.getMonth() - 1);
return new Date(now.toJSON().slice(0, 10));
}
}
I'm getting frequent errors when i start my server. Here is the error:
RangeError: Invalid time value
at Date.toISOString ()
Here is the code:
var start = timestamp;
const expiryDate = (new Date(start)).toISOString().split('T')[0];
This exception occurs when the Date object contains an invalid date.
new Date('undefined').toISOString()
In this example the Date object can be created without any problems, but the toISOString function throws an Error.
To fix your issue, you need to make sure that the timestamp variable contains a valid date string.
In my case endDate had a null value:
const [date, setDate] = useState([
{
startDate: new Date(),
endDate: null,
key: "selection",
},
]);
Changing it to new Date() solved the issue:
const [date, setDate] = useState([
{
startDate: new Date(),
endDate: new Date(),
key: "selection",
},
]);
In my case I had previously used JSON.stringify() on an object Task with an attribute duedate of type Date. Consequently taskObj.duedate became a string and did not work as a Date object in my code.
To fix the error, I converted the stringified date to Date type using taskObj.duedate = new Date(taskObj.duedate);