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')
Related
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
I'm working with duration fields on Google Spreadsheet on my timezone
Here is an example of the data I'm working with and my Spreadsheet configuration
Sample data:
actividadID
destinoID
atractivoID
actividadDescripc
actividadDuracion
actividadTipo
da839da6
ae4f25ff
'46432440
Visita
1:00:00 a. m.
EspecĂfica
Script Objective
The idea is to loop through a subset of these fields so for that I'm grabbing all the values of the spreadsheet and filtering them:
function TourDuration(tourID, mySS) {
const touractivData = mySS.getSheetByName("TourActividad").getDataRange().getValues();
const activData = mySS.getSheetByName("Actividad").getDataRange().getValues();
var current_activList = touractivData.filter(function(item){
return item[1] == tourID; //Match Bot Numbers && Unprocessed trades
});
Logger.log("current_activList:");
Logger.log(current_activList);
When I check the result of the data I'm grabbing I see data that is off, going into negative not only by hours but also by minutes:
[da839da6, ae4f25ff, 46432440, Visita a la Plaza Mayor de Lima, Sat
Dec 30 01:08:36 GMT-05:00 1899, EspecĂfica]
(This one should be the equivalent to 1 hour, but instead I got a negative time)
My goal is to add all the durations that match my filter into a consolidated one without success.
Here is the full code at the moment:
function TourDuration(tourID, mySS) {
const touractivData = mySS.getSheetByName("TourActividad").getDataRange().getValues();
const activData = mySS.getSheetByName("Actividad").getDataRange().getValues();
var current_activList = touractivData.filter(function(item){
return item[1] == tourID; //Match Bot Numbers && Unprocessed trades
});
var current_activList_length = current_activList.length;
var total_duration = 0;
for(var i = 0; i < current_activList_length; i++){
var activDuration = activData.filter(function(item){
return item[0] == current_activList[i][2]; //Match Bot Numbers && Unprocessed trades
});
var duration = Utilities.formatDate(new Date(activDuration[0][4]), "GTM-5", "dd/MM/yyyy HH:mm");
var dur2 = new Date(activDuration[0][4]).toString().substr(25,6)+":00";
dateString = Utilities.formatDate(activDuration[0][4], dur2, "MM/dd/yyyy HH:mm:ss");
Logger.log(duration)
Logger.log(dur2)
Logger.log(dateString)
total_duration = total_duration;
}
}
And this is the result of the log for a register with a 45min duration:
Could it be that the App Script interface has a different timezone?
Although the minutes difference is hard to explain since usually the differences are in full hours.
Also, I don't plan on using getDisplayValue() since I need to consult the whole sheet and getDataRange() would be more efficient.
Explanation:
Also, I don't plan on using getDisplayValue() since I need to
consult the whole sheet and getDataRange() would be more efficient.
getDisplayValues is used instead of getValues() and its purpose is to get the displayed value as it is shown in the sheet.
Please refer to this post for more details:
Difference between getValue() and getDisplayValue() on google app script
On the other hand, getDataRange() is not a sophisticated function.
This expression:
const activSheet = mySS.getSheetByName("Actividad");
const activData = activSheet.getDataRange().getValues();
is identical to this:
const activSheet = mySS.getSheetByName("Actividad");
const activData = activSheet.getRange(1,1,activSheet.getLastRow(),
activSheet.getLastColumn()).getValues();
Towards the solution:
By using getDisplayValues you will be able to get the value as it is displayed in your sheet:
function TourDuration() {
const mySS = SpreadsheetApp.getActive();
const activSheet = mySS.getSheetByName("Actividad");
const activData = activSheet.getDataRange().getDisplayValues();
console.log(activData[1][4]); // 1:00:00
}
However, you can't take the full date from this expression because the date is not specified in the cell. If you expand the change the format of your cells in column E to date:
you will see that you are getting exactly the info that is stored in the cell. So the code works as expected. The issue has to do with the missing information in the sheet itself.
You need to store the correct date in your sheet:
and then if you change the format back to time, the date will still be correct and your current script will be able to get it properly.
Unix is passed to the argument d.
I want to use much to get only the numbers but I get an error.
error message
TypeError: Cannot read property 'match' of undefined
const date = (d) => {
const dayjs = require('dayjs');
const relativeTime = require('dayjs/plugin/relativeTime');
dayjs.extend(relativeTime);
const now = Date.now();
const day = dayjs(now - d).fromNow();
console.log(day.result.match(/[0-9]*/g));
};
You cannot read property 'match' of undefined because result is undefined. Taking a look at day.js documentation, it looks like dayjs().fromNow() returns a string output directly in your day const. Be careful as the number it returns is not just in days, the breakdown could be hours/months/years based on the total number of days as you can see if the Range table when you scroll down.
const date = (d) => {
const dayjs = require('dayjs');
const relativeTime = require('dayjs/plugin/relativeTime');
dayjs.extend(relativeTime);
const now = Date.now();
const day = dayjs(now - d).fromNow(true); //pass in true to remove the suffix 'ago'
console.log(day.split(' ')[0]);
};
Instead of a regex match, all we need to do is split the string by spaces and take the first element which is the number 2 days ago -> 2
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())
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))