Set default date and time [duplicate] - node.js

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 2 years ago.
I am using Material-UI and this is their example code.
However I need the defaultValue to be today's current date and time; how can I go about this?
<TextField
id="datetime-local"
label="Next appointment"
type="datetime-local"
defaultValue="2017-05-24T10:30"
className={classes.textField}
InputLabelProps={{'
shrink: true,
}}
/>
I have tried to use something like this, however the issue is if month and day are 1-9 then how single digits and not double digits which means it won't set.
const currentdate = new Date();
const datenow = currentdate.getFullYear() + "-"
+ (currentdate.getMonth()+1) + "-"
+ currentdate.getDay() + "T"
+ currentdate.getHours() + ":"
+ currentdate.getMinutes();

You could do something like this.
const d = new Date();
const year = (d.getFullYear()).toString();
const month = ((d.getMonth()) + 101).toString().slice(-2);
const date = ((d.getDate()) + 100).toString().slice(-2);
const hours = ((d.getHours()) + 100).toString().slice(-2);
const mins = ((d.getMinutes()) + 100).toString().slice(-2);
const datenow = `${year}-${month}-${date}T${hours}:${mins}`;

Related

mongoose js Data type

Hello i have a problem with mongoose JS date type. indeed when i set date to Type:Date and then use date function to get i Get the following format and I don't know why 2022-11-02T23:00:00.000Z.
I found a solution by setting type to string and using the following code :
clientSchema.pre('save',async function(){
let currentDate = new Date();
let currentDay = `${currentDate.getDate() < 10 ? "0" :""}${currentDate.getDate()}`
let currentMonth = `${currentDate.getMonth() + 1 < 10 ? "0" : ""}${currentDate.getMonth() + 1}`
let currentYear = currentDate.getFullYear();
this.date = `${currentDay}/${currentMonth}/${currentYear}`
})
But is this the best solution or is there another ?

convert 13 digit time code to date and time stamp using moment js and get the difference between them

I have start time and end time as follows
var starttime=1631108701000
var endtime=1631116762000
var sessionstart=moment.unix(startTime);
var sessionend=moment.unix(endTime);
var ms = moment(sessionend,"DD/MM/YYYY HH:mm:ss").diff(moment(sessionstart,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var timeelapsed = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
goal is to display the starttime and endtime with proper date time stamp and disply the difference between then like 2hours16minutes53seconds or 02:16:53.The above code returns faulty data. How do I fix it?
The below code worked for me
var sessionstart= moment.unix(startTime/1000).format("DD/MM/YYYY HH:mm:ss");
var sessionend= moment.unix(endTime/1000).format("DD/MM/YYYY HH:mm:ss");
var ms = moment(sessionend,"DD/MM/YYYY HH:mm:ss").diff(moment(sessionstart,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var timeelapsed = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
By default moment.unix() expects in seconds so we need to divide by 1000 and format as per requirement.
You could also have a look at this approach. First convert unix epoch milliseconds to seconds. Then use moment's diff function to calculate the respective units. Notice that I am adding corresponding units after each diff to get the accurate difference.
const startTime = "1631108701000";
const endTime = "1631116762000";
// Converting epoch milliseconds to seconds
const startUnixTime = moment.unix(startTime / 1000);
const endUnixTime = moment.unix(endTime / 1000);
// hour difference
const hourDiff = endUnixTime.diff(startUnixTime, "hours");
startUnixTime.add(hourDiff, "hours");
// minute difference
const minDiff = endUnixTime.diff(startUnixTime, "minutes");
startUnixTime.add(minDiff, "minutes");
// second difference
const secDiff = endUnixTime.diff(startUnixTime, "seconds");
// Actual Input dates
const startDate = moment(startUnixTime).format("DD-MM-YYYY hh:mm:ss");
const endDate = moment(endUnixTime).format("DD-MM-YYYY hh:mm:ss");
console.log("Input start date", startDate);
console.log("Input end date", endDate);
// Difference in hours, minutes, seconds
console.log(hourDiff, minDiff, secDiff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

How to get month in MM and date in dd format in nodejs

I am coding in NodeJs and have to create a filename which have date and time appended. The format should be "metadata_yyymmdd_his.json". I am struggling to get the date in dd and month in MM format.
Below is the code that I have written as of now.
const dateObj = new Date();
const month = (`0${dateObj.getUTCMonth() + 1}`).slice(-2);
const date = (`0${dateObj.getUTCDate()}`).slice(-2);
const metadataFileName = 'metadata_' + dateObj.getUTCFullYear() + month + date + "_" + dateObj.getUTCHours() + dateObj.getUTCMinutes() + dateObj.getSeconds() + '.json'
How can I get the date and month prepended with 0 if it is single digit?
EX: if month is April then the result should be 04
If you're in node, don't try to roll your own datetime parsing/formatting: install and then require something that's been written specifically for that purpose, and has been tested extensively so you can rely on it working properly. A common package for that is moment.js, using its .format() function
const now = moment.now();
const formatted = moment().format("MM-DD") // or whatever other formatting you need

Performing a postgresql query using Node.js but using a variable to query with parameter

I am creating a script using node that will grab records created in the last half an hour from a PostgreSQL database. I have:
var query = client.query("SELECT * FROM users WHERE created_at>'2015-9-16 20:04:17'");
Now, my issue is that I want the created_at>'2015-9-16 20:04:17' to actually search for records created in the last half hour using a variable I have called time. The variable time is set to the last half hour:
var currentdate = new Date();
var diff=30;
var time = new Date(currentdate.getTime() - diff*60000);
var day=time.getDate();
var month=time.getMonth()+1;
var year=time.getFullYear();
var hours=time.getHours();
var minutes=time.getMinutes();
var seconds=time.getSeconds();
var time=year + '-' + month + '-' + day + ' ' + hours+':'+minutes+':'+seconds;
How do I change the query so that it searches for date>time? Originally I thought I could write:
var query = client.query("SELECT * FROM users WHERE created_at>'$time'");
You can avoid all the calculation on the client side, and instead compute the required start-time in SQL:
var query = client.query("SELECT * FROM users "
+ "WHERE created_at > (NOW() - INTERVAL 30 MINUTES)");
(I split the string purely for readability here; you don't need to do the same)
I suggest you to do:
var time=year + '-' + month + '-' + day + ' ' + hours+':'+minutes+':'+seconds;
client.query("SELECT * FROM users WHERE created_at >'" + time + "'");

Find date difference in node.js [duplicate]

This question already has answers here:
Time difference in Nodejs?
(7 answers)
Closed 8 years ago.
How to find the date of 15 days ago from the current date using Node.js?
For Eg:
Current date is - 10/JAN/2015
15 days ago is - 26/DEC/2014
There's really no need for a third party library. You can get the current time in ms and subtract 15 days worth of milliseconds from it and feed that to a new Date object:
var today = new Date();
var old = new Date(today.getTime() - (15 * 24 * 60 * 60 * 1000));
Working test harness: http://jsfiddle.net/jfriend00/f12Lfvyx/
Use moment.js
var moment = require( 'moment' );
var date1 = moment( '25/12/2014', 'DD/MM/YYYY' );
var date2 = moment( '10/01/2015', 'DD/MM/YYYY' );
var diffInMillis = date2.diff( date1 );
var diffDuration = moment.duration( diffInMillis );
console.log( diffDuration.toString() );
// to find a date 15 days ago, substract duration of 15 days
var rightNow = moment();
var before15Days = rightNow.substract( 15, 'days' );
console.log( rightNow.format( 'DD/MM/YYYY' );
console.log( before15Days.format( 'DD/MM/YYYY' );
use moment.js
moment().subtract('days', 15); // subtracts 7 days to current date
This link helps you...

Resources