how to send date as timestamp in svelte? - javascript

The svelte application is supposed to send these data to create an event to be stored in a database.
let eventName=document.querySelector('#eventName')
let timeFrom=document.querySelector('#timeFrom')
let timeTo=document.querySelector('#timeTo')
let repeatedEvery=document.querySelector('#repeatedEvery')
let startFrom=document.querySelector('#startFrom')
let endOn=document.querySelector('#endOn')
const status="upcoming"
let isRepeated=true
The dates should be sent as UNIX timestamps, I can do that just fine. The problem is to do that I had to add toString() to the variables which gives me an error of "this element is null", without it gives me 5 overload errors. I tried declaring the variable in a function that would do this process but the variables are not global anymore.
I don't want to fix the current code, I'll write the whole thing from scratch if I have to, my question is how do I actually approach this in the first place?
the dates input fields are datetime-local, and needless to say the timestamps should be a number, all the other types of data go through just fine.

Date.prototype.valueOf() returns what you need.
const dNow = new Date();
dNow.valueOf(); // 1673445066359
If you are getting null values in variables that are supose to be Dates, you can default them to a value.
const dDateDefaultToNow = theSourceValueThatYouAreUsing || new Date();
const dDateDefaultToZero = theSourceValueThatYouAreUsing || 0;
This way, if theSourceValueThatYouAreUsing is null then it will default to new Date() or 0.
For more help, please share more of your code.

Related

How can I make the number that I get from the frontend to be read as a decimal

For example if a user write 12, then when its passed to the backend to be passed as 12.00.
var contract_hrs = document.getElementById("eng_contract_hours");
you can use .toFixed(number to get value) at the time you are getting the number in backend
//in backend
let num = 12;
let n = num.toFixed(2); //12.00
Basically you cant, interaction between the two is based upon sending strings or binary. But what you can do is to create an enum for that. It will look kinda like this.
var contract_hrs = document.getElementById("eng_contract_hours");
var input_enum = {hrs: contract_hrs.value, type: int}
You can pass it to your backend and consume it the way you want based on the type property.
And in JS already 12 as a number is 12.00.

Taking time value and returning a value that will pass a moment().isValid() check

I am running some checks on a value that is passed into a timePicker on my react-native app, and I want to take a time value like 14:29, which is coming in as a string, and turn that into a value that will pass a moment(val).isValid() check.
How can I, for instance, just take today's date, but set the time to be this value of 14:29?
I tried this but it errors out:
let val = '14:29';
this._value = moment(new Date()).startOf(val);
Docs: set, startOf.
const input = '14:29';
const [hour, minute] = input.split(':');
const myMoment = moment()
.set({ hour, minute })
.startOf('minute');
console.log(
{ myMoment, isValid: myMoment.isValid() }
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Note: this will respect the browser timezone meaning different users will get different moments in time, depending on their system's currently set timezone.
To set a particular timezone you might want to use .tz(). Docs: moment timezone.

Array not emptying

Im trying to empty the array below but it it just keeps piling onto it instead of actually emptying it. Any ideas why this happens?
displaytaken[];
Edit: Adding a StackBlits:
Im getting way to confused. With the Snippet/JQ and im changing to much to get a accurate answer out of this.
Issue now is that it actually works in the stackblitz so something els is asstray will be editing it to reach a working recreation
https://stackblitz.com/edit/angular-ivy-kdec3f?
Another Edit:
Im finding it hard to recreate the issue but on the stacklits youll notice a function called checkinbetween() in there is a array called : filteredArray
This is storing data even if i clear it despite changing it from const to var so its duplicating all outputs on my side
Screenshot to help show whats happening on my side:
As u can see I clear the array but then when I add to it again the old values are there still
You are using Typescript, which gives you the added advantages of using types. Also, I would advice you to start using immutablility.
Instead of populating some 'global' array, you should create functions for you that return you the data that you need:
// Instead of this
const myDateArray: Date[] = [];
for (const someValue of someOtherDateArray) {
if (some.condition()) {
myDateArray.push(someValue);
}
}
// Do this:
function getDateArray(otherDateArray: Date[]): Date[] {
return otherDateArray.filter(date => some.condition());
}
That way, you don't need to clear the date array, as a new one can be requested on the fly.
To get to your answer, I assume you are looping over a lot of date arrays, and displaying them as taken dates in an alert box. here is how you can do that without clearing the array everytime:
const allTakenDates = [
[
new Date('2018-01-16'),
new Date('2018-03-26'),
new Date('2018-05-22'),
new Date('2018-12-01'),
new Date('2018-01-23'),
],
[
new Date('2019-01-16'),
new Date('2019-03-26'),
new Date('2019-05-22'),
new Date('2019-12-01'),
new Date('2019-01-23'),
],
[
new Date('2020-01-16'),
new Date('2020-03-26'),
new Date('2020-05-22'),
new Date('2020-12-01'),
new Date('2020-01-23'),
]
];
function getDatesAsString(dates: Date[]): string[] {
return dates.map(date => `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`);
}
for (const dates of allTakenDates) {
const formattedDates = getDatesAsString(dates).join();
alert('The following dates are taken: ' + formattedDates);
}
And here is a working example of that code.

JavaScript: global array variable returned undefined

JavaScript newbie here. I've searched and searched for answers and can't seem to figure this out. The arrays that I'm passing to a function aren't being passed as references properly. I don't think this is an async issue like many posts allude to but I could be wrong.
I have global arrays that I'm passing to a function. Inside the function, the arrays return their proper values, but when I try to access them outside of the function, they are undefined.
For context, I'm passing 3 arrays that hold the dry-bulb temperature, wet-bulb temperature, and hour that the measurements were taken for later calculations. I've only included a few sample data points for brevity. Sample code below:
function run(){
var hour = [];
var db = [];
var wb = [];
var cities = ["AB Edmonton","MI Detroit"];
getData(hour, db, wb, cities);
//this shows undefined, although within getData it is accurate data
alert(hour[1]);
}
function getData(hour, db, wb, cities){
//i= drop-down selection index, set to zero for testing
i=0;
switch(cities[i]) {
case "AB Edmonton":
hour = [1,2,3];
db = [15,18,21];
wb = [10,13,20];
break;
//case "MI Detroit":....
}
//this shows accurate values in the alert window
alert(cities[i] + " at hour:" + hour[i] + " the temp is:" + db[i]);
return [hour, db, wb];
};
run assigns empty arrays to hour, db and wb. These are variables which are locally scoped to the run function.
It then calls getData and passes those arrays as arguments.
Inside getData new local variables (also named hour, db and wb) are declared and are assigned the three empty arrays that were passed when the function was called.
The function then ignores those values and overwrites them with new arrays (these ones have contents).
It then returns another new array which holds each of those arrays.
This brings us back to run. The return value of getData is ignored completely and the original arrays (which are still stored in the hour, db and wb variables that belong to run) are accessed (but they are still empty).
You can either:
Manipulate the existing arrays inside getData instead of overwriting them. (e.g. hour = [1,2,3] may become hour.push(1); hour.push(2); hour.push(3)).
Use the return value of getData (in which case you don't need to bother assigning values or passing the empty arrays in the first place). You could use an object instead of an array so you can have useful names instead of an order here too.
Such:
function run(){
var cities = ["AB Edmonton","MI Detroit"];
var data = getData(cities);
alert(data.hour[1]);
}
function getData(cities){
//i= drop-down selection index, set to zero for testing
var i=0; // Use locally scoped variables where possible
var hour, db, wb;
switch(cities[i]) {
case "AB Edmonton":
hour = [1,2,3];
db = [15,18,21];
wb = [10,13,20];
break;
//case "MI Detroit":....
//this shows accurate values in the alert window
alert(cities[i] + " at hour:" + hour[i] + " the temp is:" + db[i]);
return { hour: hour, db: db, wb: wb];
};
Well, those aren't global variables. The one hour variable is local to run() in which it is declared with var, the other is local to getData in which it is declared as a parameter.
In your getData function you are overwriting the local variable (which initially has the value that was passed in by run()) in the line
hour = [1,2,3];
and from thereon the two variables refer to different arrays.
function getData(hour, db, wb, cities){ }
hour, db, etc are references to the initial Arrays.
When you write hour = [1,2,3];, the hour local references does not longer point to your desired Array, but to a new Array which you have just constructed: [1,2,3]. To fix this issue simply push values to the parameters
hours.push(1,2,3); so you won't overwrite your references.
This is the same problem that occurs when you do:
a = {x : 1};
function setX(obj) {
obj = {x: 2};
}
function correctSetX(obj) {
obj.x = 2;
}
The setX function will do nothing, while the correctSetX will correclty a to {x : 2}.
Thank you all for your help! I've posted how I edited my code to get it to work based on the comments. A couple things:
-I've moved all variables to be local in the getData() function. At least one of the comments gave the impression that it is better practice to keep variables local (forgive me, I am not a CSE guy by training, but I appreciate the tips and patience on your behalf)
-I wasn't able to simply use the .push method because the amount of data caused an error. (there are at least 8760 measurements per year) I can't remember the exact error but it was related to stack limits
-At the suggestion of Quentin, I instead created a dataSet object that had array properties. This object is what is returned by the getData function. Thank you again, this was a much better way to handle this
Sample below (with limited data):
function run(){
//get data
var dataSet = getData();
//test the result on the 2 hour reading
alert(dataSet.hour[1]);
}
function getData(){
//i= drop-down selection index, set to zero for testing
var i=0;
var hour,db,wb;
var cities = ["AB Edmonton","MI Detroit"];
switch(cities[i]){
case "AB Edmonton":
hour = [1,2,3];
db = [10,11,12];
wb = [13,14,15];
break;
//case "MI Detroit":...
} //end of switch
return {hour: hour, db: db, wb: wb};
}; //end of getData

Issues with Date() when using JSON.stringify() and JSON.parse()

I am trying to calculate the difference between two times using JavaScript. It's just basic math but I seem to have some issues with that while using JSON.stringify() and JSON.parse().
If you're wondering why am I applying the JSON.stringify() function to the date, it's because I using local storage to store some data on the client side and use it whenever the client lands on my website again ( it's faster that way rather than making more requests to the server ). That data usually updates once in a while ( I'm grabbing the data through API from another website ), so I set up a data_update variable and I'm storing it together with the other data.
That way I'm grabbing the stored data from the local storage and check if the difference between data_update ( which is a date / time ) and the time / date when the check it's made and see if it's greater than a week / day /etc .
So that is the reason why I'm using the JSON functions. My problem is that when I'm parsing the data from the local storage, the date seems to be different from a Date() object.
I'm trying to do the next operation per say :
var x = JSON.parse(JSON.stringify(new Date()));
var y = JSON.parse(this.get_local_storage_data(this.data_cache_key)); // the data object stored on local storage
var q = y.data_update; // this is the variable where the Date() was stored
console.log(Math.floor((x-q)/1000));
The above will return null. Also when I want to see the Math.floor(x) result, it returns null again.
So what can I do in this situation ? Is there a fix for this ?
If you look at the output of JSON.stringify for a Date, you'll see that:
JSON.stringify(new Date())
Results in a string. JSON does not have a primitive representation of Date objects that JSON.parse will turn back into a Date object automatically.
The Date object's constructor can take a date string, so you can turn those string values back into dates by doing:
var x = new Date(JSON.parse(JSON.stringify(new Date())));
Then the arithmetic will work.
x = new Date(JSON.parse(JSON.stringify(new Date())))
y = new Date(JSON.parse(JSON.stringify(new Date())))
y - x
=> 982
JSON.stringify(new Date())
returns
"2013-10-06T15:32:18.605Z"
Thank God is: Date.prototype.toISOString()
As the recommended answer suggests, the date is simply converted to a string when using JSON.stringify.
Another approach that would maybe fit this use case is to store the time in milliseconds using Date.now():
// Date.now() instead of new Date()
const millis = Date.now();
console.log(millis);
// same output as input
console.log(JSON.parse(JSON.stringify(millis)));
That way you can be sure that what goes into JSON.stringify comes out the same when using JSON.parse.
This also makes it easy to compare dates, if you have two millisecond values, using < and >.
Plus you can convert the milliseconds to a date at any time (usually before you render it to the user):
const millis = Date.now();
console.log(millis);
console.log(new Date(millis));
NOTE: using milliseconds as your date representation is usually not recommended, at least not in your database: https://stackoverflow.com/a/48974248/10551293.

Categories

Resources