I have an AJAX request that returns an array, in this array I capture the created_at from my database and it comes in the following format:
Code:
success: function(response){
let data = response;
date = data[0][`created_at`];
console.log(date);
}
log:
2022-08-25T18:44:48.000000Z
I need to split this string into two variables (date and time), what is the best way?
you can do it like this,
success: function(response){
let data = response;
date = data[0][`created_at`];
// date.split('T') - this will create an array like ['2022-08-25', '18:44:48.000000Z']
// const [date, time] - this is Array destructuring in action.
const [date, time] = date.split('T')
// date - '2022-08-25'
// time - '18:44:48.000000Z'
console.log(date, time)
}
checkout this: What does this format mean T00:00:00.000Z?
also checkout: Destructuring assignment
Let date = new Date(data[0][`created_at`]);
Console.log(date.format('dd/mm/yy'))
Try to install moment.js
Related
Date format looks like that: 2020-07-11 23:11:52
I am taking data from csv file using fetch and splitting it into single data
How to change this string (date) into date with time to plot on the chart
async function getData(){
const response =await fetch('data.csv');
const data = await response.text();
const table = data.split('\n').slice(1);
table.forEach(row =>{
const columns = row.split(',');
const date = columns[0];
// const dayshours = date.split(' ');
// const days = dayshours[0];
xlabels.push(date);
const temp = columns[1];
ytemps.push(temp);
console.log(date, temp);
});
}
Map the numbers into a string in the ISO standard, which looks like '2020-08-10T22:36:25.772'
So in your case it would look like '2020-07-11T23:11:52.000'. Note that it looks pretty much identical to what you've already got, except the T between the date and the time of day, and append .000 to the end to set the milliseconds component to zero.
Then take your string and use new Date('2020-07-11T23:11:52.000')
My Incoming Date is in format : 15.08.2017 23:03:23.120000
Here I am using Node-Red Platform to convert msg.payload.time in Influx timestamp but I am getting this Error:
"Error: Expected numeric value for, timestamp, but got '15.08.2017 23:03:23.120000'!".
Please let me know the script for given timestamp to influxdb timestamp.
InfluxDB expects unix timestamps and msg.payload.time might be a string, hence you are getting the error.
In order to generate a timeStamp from a date, you can use the Date functionality of JS.
It works in the following way:
new Date('<your-date-string>').valueOf()
Here the date-string is expected in 'YYYY-MM-DD hh:mm:ssZ' format.
In your case, since the msg.payload.time is available in dd.mm.yy hh:mm:ssZ format, you will need to perform some additional operations.
You can update your code as below:
const incomingDate = msg.payload.time;
// extract the date dd.mm.yyyy from the incoming Date String
const splittedDate = incomingDate.split(' ');
// Convert the date from dd.mm.yyyy to yyyy-mm-dd format
let date = splittedDate[0].split('.').reverse().join('-');
// Store time value in a separate variable for later use.
const time = splittedDate[1];
// merge date and time to form yyyy-mm-dd hh:mm:ssZ format
const datetime = `${date} ${time}`
// assign the timestamp value to fields.time
fields.time = new Date(datetime).valueOf();
Here is a working example
const incomingDate = '15.08.2017 23:03:23.120000';
const splittedDate = incomingDate.split(' ');
let date = splittedDate[0].split('.').reverse().join('-');
const time = splittedDate[1];
const datetime = `${date} ${time}`
console.log(datetime);
console.log(new Date(datetime).valueOf())
I'm trying to create a line graph for my project. To accomplish this I need two date inputs from a user. From there my backend takes the inputs converts it to a javascript date object.
My problem is when I'm trying to convert the date objects to a firestore timestamp I get this error.
TypeError: t.getTime is not a function
at Function.ho.fromDate (timestamp.ts:27)
at Object.next (generateReportDateRange.php:158)
at subscribe.ts:104
at subscribe.ts:233
line (generateReportDateRange.php:158) pinpoints to this code:
var toTimeStampOne = firebase.firestore.Timestamp.fromDate(dateIdOne);
What that code does is to convert the date object to a firestore timestamp object. From there I am supposed to use toTimeStampOne as a query to get certain data from documents
here is the backend end code that may be related to the problem:
var dateIdOne = sessionStorage.getItem("dateOne");
var dateIdTwo = sessionStorage.getItem("dateTwo");
var dateSetArray = [];
var dataCal = [];
console.log(dateIdOne); //OUTPUT: Fri Mar 06 2020 08:00:00 GMT+0800 (Philippine Standard Time)
console.log(dateIdTwo); //OUTPUT: Tue Mar 10 2020 08:00:00 GMT+0800 (Philippine Standard Time)
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.userId = user.uid;
} //stores the user id in variable
var toTimeStampOne = firebase.firestore.Timestamp.fromDate(dateIdOne);
var toTimeStampTwo = firebase.firestore.Timestamp.fromDate(dateIdTwo);
var dateSetArray = [];
var dataCal = [];
let userRef1 = firebase.firestore().collection("users").doc(userId).collection("glucose")
.where("dateAdded", ">=", toTimeStampOne)
.where("dateAdded", "<=", toTimeStampTwo)
.limit(7);
return userRef1.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
this.dateSet = doc.data().bgReading;
dateSetArray.push(dateSet);
this.calDateAdded = doc.data().dateAdded.toDate();
const options = {
month: 'short',
day: 'numeric',
year: 'numeric'
};
const date = new Date(calDateAdded);
const americanDate = new Intl.DateTimeFormat('en-us', options).format(date);
dataCal.push(americanDate);
});
});
});
EDIT
here is the process of the conversion
//get date input from the forms and converts it to a js date object already
var data = {
dateOne: new Date($('#dateRangeOne').val()),
dateTwo: new Date($('#dateRangeTwo').val()),
};
//stores the date object to a session storage
sessionStorage.setItem("dateOne", data.dateOne);
sessionStorage.setItem("dateTwo", data.dateTwo);
You need to do
var dateIdOne = new Date(sessionStorage.getItem("dateOne"));
var dateIdTwo = new Date(sessionStorage.getItem("dateTwo"));
because
sessionStorage.setItem("dateOne", data.dateOne);
converts date to toString()
and
fromDate is a static method from the static Timestamp class from Firebase. If you want to store a field as a timestamp in Firestore, you'll have to send a JavaScript Date object or a Firestore Timestamp object as the value of the field
I'm going to go ahead and make the call that your "date" object is not actually a JavaScript Date object. It's probably just a formatted string. You won't be able to work with this very effectively if you're trying to query Firestore timestamp fields.
You're probably going to need to change whatever the source of data is that's feeding these lines of code:
var dateIdOne = sessionStorage.getItem("dateOne");
var dateIdTwo = sessionStorage.getItem("dateTwo");
You'll need to make sure that sessionStorage.getItem returns something suitable for querying Firestore. That could be a proper date object, or some unix time in milliseconds that you can easily convert into a Timestamp.
I like to create the full code structure but I already marked an answer. Regardless I will post the code here because it might help other people.
Get input value from forms and use sessionStorage to carry it over to another page
<script>
(function(){
$('#dateForm').on('submit', async function (e) {
e.preventDefault();
var data = {
dateOne: $('#dateRangeOne').val(),
dateTwo: $('#dateRangeTwo').val(),//get date input
};
if(data.dateOne.getTime() == data.dateTwo.getTime()){
alert("Please input a valid date range! Use the specific date generator to generate a daily report");
window.location.href = "generateReport.php";
}
else if(data.dateOne.getTime() > data.dateTwo.getTime()){
alert("Please input a valid date range!");
window.location.href = "generateReport.php";
}
else{
firebase.auth().onAuthStateChanged(function(user){
if(user){
this.userId = user.uid; //stores the userid
console.log(userId);
}
sessionStorage.setItem("dateOne", data.dateOne);
sessionStorage.setItem("dateTwo", data.dateTwo);
setTimeout(function(){
window.location.href = "generateReportDateRange.php";
}, 3000);
});
}
});
})
();
</script>
The query code (Getting document data based on two Firestore timestamp objects)
<script>
var dateIdOne = new Date(sessionStorage.getItem("dateOne"));
var dateIdTwo = new Date(sessionStorage.getItem("dateTwo"));
firebase.auth().onAuthStateChanged(user => {
if(user){
this.userId = user.uid;
} //stores the user id in variable
var toTimeStampOne = firebase.firestore.Timestamp.fromDate(dateIdOne);
var toTimeStampTwo = firebase.firestore.Timestamp.fromDate(dateIdTwo);
let userRef1 = firebase.firestore().collection("users").doc(userId).collection("glucose")
.where("dateAdded", ">=", toTimeStampOne)
.where("dateAdded", "<=", toTimeStampTwo)
.limit(7);
//PERFORM GET DOC DATA HERE
});
</script>
Frontend: React
Backend: SpringBoot
Date format on the BE: 2011-10-05T14:48:00.000Z
I've tried to use the date-fns to send the correct format from the FE to the BE application, ut even following the documentation, the BE is receiving null.
Salvar = async () => {
const {update} = this.state;
const {dtInclusao} = this.state.compra.dtInclusao
var result = parse(
dtInclusao,
"dd/mm/yyyy",
new Date()
)
const response = await api.post('SolicCompra/compra',
{...this.state.compra, dtInclusao: result}, {'Content-type':
'application/json'});
The expected format is dd/MM/yyyy.
Here are some date-fns helpers I use on a regular basis:
export const parseDate = dateString => {
return Date.parse(dateString.replace(/-/g, '/').replace('T', ' '))
}
export const formatDate = date => {
return format(date, 'dd/MM/yyyy')
}
The first will parse date and timestamps into a Date object. The second will take that date object and format it back to a string in the format you want.
Using these helper functions you can update your code to:
var result = formatDate(parseDate(dtInclusao))
I'm making a task management widget that displays tasks based on if they are in the current day, week or month. I'd like to push dates into weeklyTaskArray, dailyTaskArray, monthlyTaskArray and render them using .length.
This is what I've tried and the "if" statement runs but pushes all data into dailyQuoteArray/weeklyQuoteArray etc:
$http({
method: 'GET',
url: 'http://localhost:3000/api/quotes.json',
responseType: "json"
}).then(function(response) {
let quotes = response.data;
angular.copy(quotes, quoteArray)
quotes.forEach(function (element) {
let currentDate = element.expiration_date;
console.log(currentDate);
var moment = require('moment')
var todaysDate = moment("05/17/2016");
var date2 = moment(currentDate)
var answer = moment(todaysDate).diff(date2, "days")
console.log("this is the answer", answer);
if (answer >= 2) {
dailyQuoteArray.push(answer)
}
if (answer <= 7) {
weeklyQuoteArray.push(answer)
console.log("weeklyquotear length", weeklyQuoteArray.length);
}
})
});
You should convert your expression to javascript date object. You can use momentjs for date operations like converting or comparing.
var date = moment("05/17/2017", "DD/MM/YYYY")._d;
Use ´date.parse()´ to create a JavaScript Date
new Date("05/17/2017"); //Wed May 17 2017 00:00:00