Trying to get first date of current month in html date picker - javascript

Hi I am trying to get first date of current month in HTML date picker.
From <input type="date" id="fdate" value=""/>
To<input type="date" id="tdate" value=""/>
I get today date in id="tdate like this given below but starting date of current month not able to get as I get current date.
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year + "-" + month + "-" + day;
document.getElementById("tdate").value = today;
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
document.getElementById("tdate").value = firstDay;

date input fields must be in YYYY-MM-DD format. Your code:
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
Will give back a string, e.g. Tue Sep 01 2020 00:00:00 GMT-0400 (Eastern Daylight Time), which is not what you want.
You can combine a couple of existing StackOverflow answers to accomplish what you want:
// https://stackoverflow.com/a/23593099/378779
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
// https://stackoverflow.com/a/13572682/378779
function getFstDayOfMonFnc() {
var date = new Date();
return new Date(date.getFullYear(), date.getMonth(), 1)
}
Assuming fdate should be the first of the month and tdate should be today's date:
document.getElementById('fdate').value = formatDate( getFstDayOfMonFnc() );
document.getElementById('tdate').value = formatDate( new Date() );

var date = new Date();
var monthStart = Date.UTC(date.getFullYear(), date.getMonth())
monthStart = toIsoDateString(monthStart);
console.log(monthStart);
var nextMonthStart = Date.UTC(date.getFullYear(), date.getMonth() + 1);
nextMonthStart = toIsoDateString(nextMonthStart);
console.log(nextMonthStart);
function toIsoDateString(utcDate) {
var date = new Date(utcDate);
return date.toISOString().split('T')[0];
}

I also had made such a program but there were a few changes, instead of just the first date I was getting the current time, the first day of the month and also the last date of the month.
This is the code I used:
<html>
<head>
<title>JavaScript Dates</title>
</head>
<body>
<script>
var date = new Date();
document.write("Current Date: " + date );
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
document.write("<br>"+firstDay);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
document.write("<br>"+lastDay);
</script>
</body>
</html>
You can edit this code and try working out.

Related

how to change dateformat into yyyy-mm-dd

I am using AIR DATEPICKER plugin for one of my page for datetime field.now I able to get the date format on placeholder by default 2022-09-01 . but when I select date from datetime calender it's showing me value like 22 September 2022 00:00 am . I want to get date value in 2022-09-22 00:00 am So how can I change dateformat?
Here Is my code:
<input type="text" class="form-control col-md-2 datetimepicker d-inline" id="dfield" name="scheduleField" value=""/>
Javascript code:
const dateInput = document.getElementById("dfield");
// Using the visitor's timezone
//dateInput.value = formatDate();
dateInput.value = new Date().toISOString().split("T")[0];
function padTo2Digits(num) {
return num.toString().padStart(2, "0");
}
function formatDate(date = new Date()) {
return [
date.getFullYear(),
padTo2Digits(date.getMonth() + 1),
padTo2Digits(date.getDate()),
].join("-");
// dateInput.value = new Date().toISOString().split('T')[0];
}
Try this
function formatDate() {
var d = new Date(),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
console.log(formatDate());

I calculated to get the first day of the month but go the last

I start by getting the date of the beginning of month:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
Then I convert it to ISO:
firstDay = firstDay.toISOString();
Why did I get 2019-05-31 as the first day instead of 2019-06-01?
You could use a simple regex to format the string using replace:
/(\d{4})-(\d{2})-(\d{2}).+/
// Set the inital date to a UTC date
var date = new Date(new Date().toLocaleString("en-US", {timeZone: "UTC"}))
// Update the day without affecting the month/day when using toISOString()
date.setDate(1)
// Format the date
let formatted = date.toISOString().replace(/(\d{4})-(\d{2})-(\d{2}).+/, '$3-$2-$1')
console.log(formatted)
The default javascript date uses your local timezone, by converting it to something else you can end up with a different date.
You can do it
var firstDay = new Date().toISOString().slice(0, 8) + '01';
console.log(firstDay);
The date object in javascript can be somewhat tricky. When you create a date, it is created in your local timezone, but toISOString() gets the date according to UTC. The following should convert the date to ISO but keep it in your own time zone.
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var day = 0;
if (firstDay.getDate() < 10) {
day = '0' + firstDay.getDate();
}
var month = 0;
if ((firstDay.getMonth() + 1) < 10) {
//months are zero indexed, so we have to add 1
month = '0' + (firstDay.getMonth() + 1);
}
firstDay = firstDay.getFullYear() + '-' + month + '-' + day;
console.log(firstDay);

add getTime from date to another date without time javascript

I need to add getTime from giving the date to another date format yyyy-mm-dd using javascript.
this is my date :
var m = new Date(res[i].DATESTART).getTime();
add m to another date.
var ddm = formatDate(monday);
var dddm = ddm+" 23:59:59";
var newdate = new Date(dddm);
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}

Change date range in javascript

I am trying to set start and end date in date picker where start date is week before current date and end date is week after start date. In certain condition it gives me 0 for start date. Can anyone look into code below and help me to get proper date range when current date is first day of the month or last date of the month. Thanks for your help.
var date = new Date();
//When current date was less then 7 in some situation it giving me error. So, I am checking current date and randomly subtract 3.
//if current date is less then 7 then get the last day of the previous month
if (date.getDate() <= 7) {
day = new Date(date.getFullYear(), date.getMonth(), 0);
startdate = day.getDate() - 3;
month = day.getMonth() + 1;
year = day.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = day;
console.log("App Config: lasy day: " + startdate + "\nmonth: " + month + "\nyear:" + year);
}
else {
startdate = date.getDate() - 7;
month = date.getMonth() + 1;
year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = day;
console.log("App Config: day: " + startdate + "\nmonth: " + month + "\nyear:" + year);
}
return month + "/" + startdate + "/" + year;
Have you tried this:
var dt = new Date();
var weekBefore = dt.setDate(dt.getDate() - 7);
var weekAfter = dt.setDate(dt.getDate() + 7);
JavaScript will figure it out automatically the date 7 days before and after!
If you are ok with plugins I would suggest Moment.js which is great for date handling. Adding a week would be as easy as
var inOneWeek = moment().add(1, 'weeks');//.format('DD/MM/YYYY'); if u want it in DD/MM/YYYY format
var oneWeekAgo = moment().add(-1, 'weeks');//.format('DD/MM/YYYY');
otherwise #sabotero's answer would do as well.

Date Convert in jquery

I need DD-MM-YYYY Format of the given date.
var todaydate = /Date(1394908200000)/; //Serialize date
var date = eval("new " + todaydate.replace(/\//g, ""));
alert('date is :'+date)
but output look like,
date is :Wed Jun 11 2014 00:00:00 GMT+0530 (India Standard Time)
Expected output like,
date is :11-06-2014
Try this
var date = new Date(); //new Date(1394908200000)
function convert(str) {
var date = new Date(str),
mnth = ("0" + (date.getMonth() + 1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
return [day, mnth, date.getFullYear()].join("-");
}
var final = convert(date);
alert('date is :' + final)
DEMO
Besides of JS like other people mention, you can also use the .datepicker from jquery ui plug-in
var dt = $.datepicker.formatDate('dd-mm-yy', new Date(1394908200000));
alert(dt);
JSFiddle, use jquery ui plug-in
WORKING FIDDLE
Try this-
var date = new Date();
function myDateFormatter (dateobject) {
var d = new Date(dateobject);
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if (day < 10) {
day = "0" + day;
}
if (month < 10) {
month = "0" + month;
}
var date = day + "-" + month + "-" + year;
return date;
};
var dateformat = myDateFormatter(date);
alert('date is :' + dateformat);

Categories