How to create date object from string retrieved from JSON? - javascript

I would like to create a new Javascript date object and save it to a variable all from a JSON endpoint route. The JSON looks like this:
[
{
"class_instructor": 1,
"id": 1,
"location": "Boise",
"start_date_time": "Thu, 19 Nov 2020 09:10:00 GMT"
},
{
"class_instructor": 1,
"id": 2,
"location": "Meridian",
"start_date_time": "Mon, 16 Nov 2020 09:10:00 GMT"
}
]
I have been able to grab each objects value through iteration using Axios and saving it to a variable, however I would like to generate a javascript date object from the start_date_time value's strings. I am sure I can grab each of character of the string and eventually create the date object by individually adding each year, month, day... let this_date = new Date(2020, 11, 19, 9, 10)
However, this doesn't appear to be fullproof and there has got to be an easier way.

use this to create new date from your string
var getDateFrom = array[0].start_date_time;
var setDateTo = new Date(getDateFrom);
//this sets date using string format like you have

it is simple you need just to call Date with your string.
const a= new Date('Thu, 19 Nov 2020 09:10:00 GMT')
or in general :
const a= new Date('start_date_time')
you can verify that in console, when you click . after a a.
the properties and functions of the Date type will appear.

Related

Using ISODate with mongodb query and node.js

I am creating a string -
queryString - {"Project": "Serenity","DateOfWalkin": {"$gte": "2022-03-01" ,"$lt": "2022-03-31"} }
then parsing it - queryObject = JSON.parse( queryString )
It is parsing successfully, but when I run the query it does not give me any result.
Now when I update the same query by using ISODate for both dates, and then tried running the query in Mongo compass, it works fine.
I want to use ISODate() but the problem is the way I am building the queryString is based on different conditions from the user input, now if a particular condition is true then and only then I want to query that particular field. For other fields I am searching, which are of type "String" in my db, I am able to get the correct result, but for date I am facing this issue.
startDate and endDate are user inputs using date picker in HTML
TRIAL number 1
queryString = queryString + ,"DateOfWalkin": {"$gte": ISODate("${startDate}")} ,"$lt": { "$date" : ISODate("${endDate}") } }
This will give a parser error saying identifier "I" not found, hence I am not able to parse this string.
To combat this, I tried to use new Date object, tried to convert the date using toISOString, but it didn't work.
TRIAL number 2
queryString = queryString + ,"DateOfWalkin": {"$gte": "ISODate("${startDate}")"} ,"$lt": { "$date" : "ISODate("${startDate}")" } }
If we use double quotes for ISODate as well, it will solve the parser issue but Mongo query will not give any result and it is treating ISODate wrapper as a string literal.
TRIAL number 3
queryString = queryString + ,"DateOfWalkin": {"$gte": "${startDate}"} ,"$lt": { "$date" : "${endDate}" } }
Does not give result
TRIAL number 4
Using new Date() to get the ISODate format
Query becomes -
{
Project: 'Serenity',
DateOfWalkin: {
'$gte': 'Tue Mar 01 2022 05:30:00 GMT+0530 (India Standard Time)',
'$lt': 'Thu Mar 31 2022 05:30:00 GMT+0530 (India Standard Time)'
}
}
Still it doesn't give any result
TRIAL number 5
Query object -
{
Project: 'Serenity',
DateOfWalkin: {
'$gte': { '$date': '2022-03-01' },
'$lt': { '$date': '2022-03-01' }
}
}
Above doesn't give result
Is there any way I can store the value of ISODate("${startDate}") and use that variable in the main queryString?
Or is there a better way to compare dates when I am using the input dates as user input?
I have tried multiple approaches and kinda feeling stuck at this point.
Why do you parse the string?
Apart from your current problem, you also open the door for NoSQL-Injection. You can compose the query object also directly like this:
const queryObject = {};
queryObject["Project"] = "Serenity";
queryObject["DateOfWalkin"] = { $gte: ISODate("2022-03-01"), ["$lt"]: ISODate("2022-03-31") };
const ninDates = [];
ninDates.push(ISODate("2022-03-10"));
ninDates.push(ISODate("2022-03-20"));
queryObject["DateOfWalkin"]["$nin"] = ninDates;
db.collection.find(queryObject)
If you really insist to parse the string, then use ejson
EJSON.parse('{ "Project": "Serenity", "DateOfWalkin": { "$gte": { "$date": "2022-03-01" }, "$lt": { "$date": "2022-03-01" } } }')
Should give desired queryObject. Note, keys and values need to be enclosed by double-quotes (")

Date objects in dictionaries change timezone in Javascript/Node

To avoid day light saving issues with date objects, I use UTC. For example:
new Date(2019,8,20, 9, 0) gives 2019-09-20T08:00:00.000Z
new Date(Date.UTC(2019,8,20, 9, 0)) gives 2019-09-20T09:00:00.000Z -- what I want
My issue now is that when I add that date to a dictionary, It uses local timezone somehow. For example:
const b = {}
b[Date(Date.UTC(2019,8,20, 9, 0))] = true
gives the following:
{ 'Fri Sep 20 2019 10:00:00 GMT+0100 (IST)': true }
you can do the following to get the UTC time -
var utcDate = new Date(Date.UTC(2019,8,20,9,0)).toUTCString()
b[utcDate] = true
EDIT
You should use ISOString() format to get format like 2019-09-20T09:00:00.000Z
var utcDate = new Date(Date.UTC(2019,8,20,9,0)).toISOString()
b[utcDate] = true

How do I create a JSON string from data stored in Google Firebase

I need my Google Firebase Database Data converted to a JSON string.
The desired outcome should be as follows:
var dataSet =[
{arr:"test",des:"DMM",eta:"17 Feb 2018 11:00",etd:"17 Feb 2018 13:30",gate:"S92", inbound:"RT456", org:"ARN", outbound:"RT678", remarks:"CHARTER", sta:"17 Feb 2018 11:00", std:"17 Feb 2018 13:30", whs:"T11"},
{arr:"test",des:"ESB",eta:"17 Feb 2018 09:00",etd:"17 Feb 2018 15:30",gate:"S94", inbound:"SD941", org:"JNB", outbound:"SD942", remarks:"", sta:"17 Feb 2018 09:00", std:"17 Feb 2018 15:30", whs:"T11"}
];
I'm new to this and have therefore no clue how to accomplish this.
First get the DataSet-schedule object and then iterate for each of the objects inside it :
dbRef.child("DataSet-schedule").once("value").then(
function(snapshot){
var dataSetObj = snapshot.val(), text= "";
for(x in dataSetObj){
text += JSON.stringify(dataSetObj[x]);
text+= "--"; //separator
}
var result = text.split("--");
result.pop();
}
);
The JSON data is available at https://your-project.firebaseio.com/.json. You can obtain this by sending a GET request to this url. If you have classes in your data and would like to get the data for a particular class instead, use https://your-project.firebaseio.com/your-class.json
You can test this by using curl https://your-project.firebaseio.com/.json
For better readability you can use curl https://your-project.firebaseio.com/.json?print=pretty
Refer: https://firebase.google.com/docs/database/rest/retrieve-data
You can also export to JSON from your console. Open three dot icon and there will be export and import feature.

Why is moment.js giving different results when assigned to a variable?

I have been debugging this for a little while now and still haven't been able to figure it out. Look specifically at the how the time in _d differs from the time in _i. Why?
var date = new Date('Fri, 06 Jan 2017 21:30:00 -0000')
const momentDate = moment(date)
console.log(`momentDate: `, momentDate);
console.log(`moment(date): `, moment(date));
So what was causing the problem was I had a react component that was overwriting the values to startOf('day'). If you're using moment to convert all your string dates flowing into your application into moment objects, if you experience bugs, make sure to look in your component and not just at the convertToMoment massaging functions for the API calls.
More importantly, until moment 3.0, all moment objects are mutable so if you do:
var a = moment()
var b = a.startOf('day')
console.log(a.format('LLL')) // January 22, 2017 12:00 AM
console.log(b.format('LLL')) // January 22, 2017 12:00 AM
The only way to fix this is either:
// use the cool `frozen-moment` package (which is basically a polyfill)
var a = moment().freeze()
var b = a.startOf('day')
console.log(a.format('LLL')) // January 22, 2017 2:17 AM
console.log(b.format('LLL')) // January 22, 2017 12:00 AM
// or type `.clone()` everytime you want to use a cool function
var a = moment()
var b = a.clone().startOf('day')
console.log(a.format('LLL')) // January 22, 2017 2:17 AM
console.log(b.format('LLL')) // January 22, 2017 12:00 AM

How to convert JSON (OData) time in something like gg-mm-aaaa in Javascript?

I've a JSON like this ...
{
"d": {
"__count": "5798",
"results": [{
"time": "\/Date(1467039720000+0120)\/",
"internalId": "5771271b84aed43d477c901b",
"datasetVersion": 3,
"idDataset": "1214",
}, {
"time": "\/Date(1467036120000+0120)\/",
"internalId": "577118c784aed43d477bdf90",
"datasetVersion": 3,
"idDataset": "1215",
.....
and I'd like to extract and convert the time in a format like gg-mm-aaaa using javascript (or PHP if necessary ...).
Note that I know that "+120" are minutes ... so 2 hours.
Is there any javascript library or code sample to make this transformation?
Moment JS is a very good library for dealing with time / dates. You'll probably need to parse out the string value in your JSON to send it to moment though.
http://momentjs.com/
Try This
function FormatDate(value) {
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(value);
var dt = new Date(parseFloat(results[1]));
console.log(dt);
console.log(dt.getMonth());
console.log((dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear());
}
For example
FormatDate("/Date(1467039720000+0120)/");
Output:
Mon Jun 27 2016 11:02:00 GMT-0400 (US Eastern Daylight Time)
VM64:50 5
VM64:51 6/27/2016
Here is the fiddle link:
https://jsfiddle.net/jkqm4ej3/

Categories