ReactJS Moment is not formatting date correctly - javascript

I have a function for displaying the first date of the week and it's result are displayed as followed:
Mon Nov 12 2018 08:14:09 GMT-0600 (Central Standard Time)
...what am attempting to do is display the result with the month only:
2018-11-12
...here is the function for getting the first day of the week:
let sd = new Date();
const startOfWeek = (date) => {
let diff = date.getDate() - date.getDay() + (date.getDay() === 0 ? -6 : 1);
return new Date(date.setDate(diff));
}
...I call the function as followed:
const startDay = startOfWeek(sd).toString();
...Here is where I Use moment to apply the formatting:
moment(startDay).format('YYYY MMMM Do');
...but my date still displays the following:
Mon Nov 12 2018 08:14:09 GMT-0600 (Central Standard Time)
...could I get some help as to what am doing wrong?

I think the moment js format you are looking for is:
moment(startDay).format('YYYY-MM-DD');
The format YYYY MMMM Do would return a string like: "2018 November 13th".

This should work, the format was incorrect though, it should be YYYY-MM-D
let sd = new Date();
const startOfWeek = (date) => {
let diff = date.getDate() - date.getDay() + (date.getDay() === 0 ? -6 : 1);
return new Date(date.setDate(diff));
}
const startDay = startOfWeek(sd)
console.log(moment(startDay).format('YYYY-MM-D'));

Related

How to get current month datas from mysql using javascript?

I have table of records and need to get only current month records.
CODE:
let startDate = req.body.startDate
let endDate = req.body.endDate
let result = await caseRegistration.findByDate({ pathology_id : req.body.pathology_id,
created_at: {
'>=': new Date(startDate),
'<=': new Date(endDate)
}
})
Above code I am passing particular dates to get records. But my requirement is If request doesn't have any date then I want to get only current month data. Can you please help me?
var date = new Date();
var firstDay = new Date(date.getFullYear(),date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(),date.getMonth(), daysInMonth(date.getMonth()+1,
date.getFullYear()));
firstDay=>Tue Sep 01 2020 00:00:00 GMT+0530 (India Standard Time)
lastDay=> Wed Sep 30 2020 00:00:00 GMT+0530 (India Standard Time)
Please take care of timezone & date formate you want(it could be any)
If startDate and endDate are empty find first date and last date of current month by using this :
var date = new Date();
var firstDateOfCurrentMonth = new Date(date.getFullYear(), date.getMonth(), 1);
var endDateOfCurrentMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0);
Now you can assign these dates to startDate and endDate
statDate=firstDateOfCurrentMonth;
endDate=endDateOfCurrentMonth;

Javascript setting date not working ok Chrome

Here's an issue I'm getting setting a date with Javascript on Chrome
"17-09-2019"
var [day, month, year] = date.split('-');
undefined
day
"17"
month
"09"
year
"2019"
var set_date = new Date(parseInt(year), parseInt(month), parseInt(day));
undefined
console.log(set_date);
VM5577:1 Thu Oct 17 2019 00:00:00 GMT+0300 (East Africa Time)
undefined
So I have a date 17-09-2019 and point here is 09 is September but when I set the date I get back October.
Been scratching my head over this one for a while now. Not sure what's going on.
The months in javascript starts from 0. You just need to subtract 1 to your parseInt(month):
var date = "17-09-2019";
var [day, month, year] = date.split('-');
console.log(`${day}-${month}-${year}`)
var set_date = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
console.log(set_date);
Set out this , month starting from index 0
var date = "17-09-2019"
var [day, month, year] = date.split('-');
month = month - 1;
var set_date = new Date(parseInt(year), parseInt(month), parseInt(day));
console.log(set_date); //Tue Sep 17 2019 00:00:00 GMT+0530 (India Standard Time)

How to set time with AM PM in Javascript Date Object

Say that I have DateTime in this format Fri Feb 02 2018 00:00:00 GMT+0530 (IST)
And from the time picker plugin getting the time 1:10am or 2:30pm in this format.
I am not sure how to calculate and combine/add them both to produce this result:
Fri Feb 02 2018 01:10:00 GMT+0530 (IST) or Fri Feb 02 2018 14:30:00 GMT+0530 (IST)
I wish if there was something to do as simple as this:
new Date(dateString).setHours(1:10am)
Seems like you need to parse it on your own:
function parseDaytime(time) {
let [hours, minutes] = time.substr(0, time.length -2).split(":").map(Number);
if (time.includes("pm") && hours !== 12) hours += 12;
return 1000/*ms*/ * 60/*s*/ * (hours * 60 + minutes);
}
To add it to a date:
new Date(
+new Date("Fri Feb 02 2018 00:00:00 GMT+0530")
+parseDaytime("1:20pm")
);
Here is a simple function to do what your after.
It basically splits the time using a regex, and then calls setHours & setMins, adding 12 hours if pm is selected.
The example below takes the current datetime, and sets 1:10am & 2:40pm..
function setHours(dt, h) {
var s = /(\d+):(\d+)(.+)/.exec(h);
dt.setHours(s[3] === "pm" ?
12 + parseInt(s[1], 10) :
parseInt(s[1], 10));
dt.setMinutes(parseInt(s[2],10));
}
var d = new Date();
console.log(d);
setHours(d, "1:10am");
console.log(d);
setHours(d, "2:40pm");
console.log(d);
You can parse the time string into hours & minutes, adjust the hours according to am/pm & set it to the date object then:
var dateString = 'Fri Feb 02 2018 00:00:00 GMT+0530 (IST)';
var hoursString = '2:30pm';
var parts = hoursString.replace(/am|pm/, '').split(':')
var hours = parseInt(parts[0]) + (hoursString.indexOf('pm') !== -1 ? 12 : 0);
var minutes = parts[1];
var date = new Date(dateString);
date.setUTCHours(hours, minutes);
console.log(date); // in your local time
console.log(date.toUTCString()); // in UTC (i.e. without timezone offset)
(Note setHours / setUTCHours mutates date object but returns unix timestamp of the updated datetime.)

convert date format to 'YYYYMMDD'

In Javascript, I have date string as shown below:
var dateStr = "Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)";
I need to convert it to "YYYYMMDD" format. For example the above date should be : "20150325"
A good function for doing that which I found and used it always.
Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();
return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('');
};
var date = new Date();
date.yyyymmdd();
Here's a dirty hack to get you started. There are numerous ways of achieving the format you want. I went for string manipulation (which isn't the best performance).
var someDate = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");
var dateFormated = someDate.toISOString().substr(0,10).replace(/-/g,"");
alert(dateFormated);
function getFormattedDate(date) {
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return year + month + day;
}
And then just call the function :
alert(getFormattedDate(new Date());
The Date object is able to parse dates as string d = new Date( dateStr ); provided that they are properly formatted like the example in your question.
The Date object also offers methods to extract from the instance the year, month and day.
It's well documented and there are plenty of examples if you just Google for it.
What is worth mentioning is that the Date object doesn't handle timezone and the internal date-time is always converted into the client's timezone.
For example here's what I get if I try to parse your date in my browser (I'm in GMT+01):
dateStr = "Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)";
d = new Date( dateStr );
---> Wed Mar 25 2015 01:00:00 GMT+0100 (CET) = $2
If you need to handle timezone properly the easiest way is to use a library like MomentJS

JS: Change Date format returned from DatePicker

I'm not that good at JS, so I have a problem with dates.
I want to set range for my DatePickers - that's why when the date is changed, I get it in the following format:
Wed Jul 08 2015 00:00:00 GMT+0200 (CEST)
I need to change it to the date in format dd/mm/yyyy to use the value later. Till now it looks like following:
var nowTemp = new Date();
$("#datepickerStart").on("changeDate", function (e) {
minDate = e.date;
console.log(minDate); // Wed Jul 08 2015 00:00:00 GMT+0200 (CEST)
// day = minDate.getDate(); <- doesn't work
// monthIndex = minDate.getMonth();
// year = minDate.getFullYear();
});
$('#datepickerStart').datepicker({
format: "dd/mm/yyyy",
startDate : new Date('01/01/2009'),
endDate : new Date()
});
$('#datepickerEnd').datepicker({
format: "dd/mm/yyyy",
startDate : minDate,//""+day+"/"+monthIndex+"/"+year,<- tried different approaches
endDate : new Date()
});
If I use minDate.format("dd/mm/yyyy"), it returns error "Uncaught TypeError: minDate.format is not a function".
Thanks in advance for help.
A good alternative for doing this is using momenjs library.
Other alternative is that you create a function which formats your date as follow:
var formatDate = function(d) {
var date = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
var newDate = (date < 10 ? ('0' + date) : date) + '/' + (month < 10 ? ('0' + month) : month) + '/' + year;
alert(newDate);
}
// Usage example
var now = new Date();
formatDate(now)

Categories