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 ?
Related
I am trying to validate or check the date range by passing month and year, If date range come under the given month range between, then it would be valid else error.
month = "04, 06, 2022"; // from-month, to-month, year
date = "12-05-2022" // DD-MM-YYYY
from month = 04
to month = 06
year = 2022
I read the documentation but didn't achive the goal.
I want if I am passing this data below -
month = "04, 06, 2022"; // from-month, to-month, year
date = "12-07-2022" // DD-MM-YYYY => error
date = "12-05-2022" // DD-MM-YYYY => success
let value = '12-05-2022'; //DD-MM-YYYY
let check = moment(value,'DD-MM-YYYY', true).isValid();
console.log(check) //returns true
return check
Try to use a range to check if the date corresponding to value is contained:
const year = 2022;
const fromMonth = 4;
const toMonth = 6;
const startDate = new Date(year, fromMonth, 12);
const endDate = new Date(year, toMonth, 15);
const value = '12-05-2022';
const check = moment().range(startDate, endDate).contains(new Date(value));
console.log(check);
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>
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}`;
I have a table that contains a year column, but the generated model does not seem to be able to search by year as I would expect.
Year model:
integer (Year) {
description (Description for Year)
}
Autogenerated js:
var dates = require('dates')
exports.timeToMili = timeToMili
function timeToMili(time) {
//TODO consider zone offset
var timeStr
if (time instanceof Object && "hour" in time) {
var hour = ("amPm" in time && String(time.amPM) == 'Pm') ? Number(time.hour) + 12 : Number(time.hour)
var minute = ("minute" in time && time.minute ? time.minute : "00")
//sanity check
timeStr = hour + ":" + (String(minute).length < 2 ? "0" + minute : minute)
return dates.ZonedDateTime.parseTime(timeStr, "H:mm").getMillisFromEpoch()
}
return null //TODO error handling
}
This training worked:
[g:CO2Concentration] Show the CO2 concentration for (1967)[v:Year]
The key was finding that "Year" was the correct Node to select.
Hello i get my date from Datepicker that gets saved to a string then uploaded to Firebase. The string is then recieved to the phone. The problem is that i want to convert this string to NSDate when i retrieve it.
This is how i get a string from datepicker
func datePickerChanged(datePicker:UIDatePicker){
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
var strDateFrom = dateFormatter.stringFromDate(datePicker.date)
fromDate = strDateFrom
print(fromDate)}
When i retrieve the date i get it as a string this is the print
print(self.membershipActiveTo)
And this is the print log
5/11/16, 2:35 PM
And below is the line of code i have tried to convert to string but it only returns nil
let strDate = self.membershipActiveTo // "2015-10-06T15:42:34Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm"
print ( dateFormatter.dateFromString( strDate ) )
There are things to consider when working with dates and one of them is how to store the date in a consistent format that can be easily worked with for different uses. In your case, you may want to sort by date and if the data is stored like this
5/11/16, 2:35 PM
It's not going to be sortable. So, a different format is needed and here's one possible example
20160511143500
Here's some code to manipulate dates:
Write a nicely formatted date to Firebase
let d = NSDate()
//create a custom date string & save in firebase
let dateFormatterCustom = NSDateFormatter()
dateFormatterCustom.dateFormat = "yyyyMMddhhmmss"
let customDateString = dateFormatterCustom.stringFromDate(d)
print(customDateString) //prints "20160511023500" just for testing
let timesRef = self.myRootRef.childByAppendingPath("time_test")
let thisTimeRef = timesRef.childByAutoId()
let timeChildRef = thisTimeRef.childByAppendingPath("timestamp")
timeChildRef.setValue(customDateString)
Firebase now has this
time_test
-KFerAcANQv4pN1Pp4yW
timestamp: "20160418033309"
Then to read in from Firebase:
let timesRef = self.myRootRef.childByAppendingPath("time_test")
timesRef.observeEventType(.ChildAdded, withBlock: { snapshot in
let timeStamp = snapshot.value.objectForKey("timestamp") as! String
print(timeStamp) //still looks like 20160418033309
let shortDateString = self.timeStampToDateString(timeStamp)
print(shortDateString) //prints 4/18/16, 3:33 AM
})
and the function that converts the timestamp style string to a human readable one
func timeStampToDateString(stamp: String) -> String {
//create a custom date string & create a date object from it
let dateFormatterCustom = NSDateFormatter()
dateFormatterCustom.locale = NSLocale(localeIdentifier: "US_en")
dateFormatterCustom.dateFormat = "yyyyMMddhhmmss"
let d = dateFormatterCustom.dateFromString(stamp)!
//create a short date style string and format the string
let dateFormatterShortStyle = NSDateFormatter()
dateFormatterShortStyle.dateStyle = NSDateFormatterStyle.ShortStyle
dateFormatterShortStyle.timeStyle = NSDateFormatterStyle.ShortStyle
let dateString = dateFormatterShortStyle.stringFromDate(d)
return dateString
}
There's a lot of extra code in this example so it could be shortened considerably but I wanted to leave in all of the steps.