HTML Date : Get Correct date in yyyy - mm - dd - javascript

I am using HTML date function and javascript to get exact date in YYYY-mm-dd. its working fine for me except for 1st day of the month.
Ex: 1st Feb 2016 is converted to 2016-01-32
function mydate1(cachedDate) {
var today = new Date();
console.log(today);
if (cachedDate === undefined) {
console.log("no cached value found");
var d = new Date(document.getElementById("dt").value);
sessionStorage.setItem('dateCached', document.getElementById("dt").value);
console.log(d);
//sessionStorage.setItem('dropdownCached',document.getElementById("s1").value);
console.log("set session value :" + sessionStorage.getItem('dateCached'));
} else {
var d = new Date(cachedDate);
console.log(document.getElementById("dt").value);
sessionStorage.setItem('dateCached', d);
console.log("set session value :" + sessionStorage.getItem('dateCached'));
}
if (today < d) {
alert("No Record Found ..... ");
return;
}
dt = d.getDate();
dt++
dt = ('0' + dt).slice(-2);
mn = d.getMonth();
mn++;
mn = ('0' + mn).slice(-2);
yy = d.getFullYear();
var x = yy + "-" + mn + "-" + dt;
document.getElementById("ndt").value = dt;
ajaxFunction('dt');
console.log(x);
}
<input type="date" class="form-control" id="dt" onchange="mydate1();" />
<input type="text" id="ndt"/>
I tried couple of solutions from google but nothing is working for me .. can some one help me fixing the script.

First, you shouldn't need to increment the value returned by getDate(), because
the value returned by getDate() is an integer between 1 and 31.
This is in contrast to getMonth(), where
The value returned by getMonth() is an integer between 0 and 11.
Second, you might try specifying the time zone when you construct the new Date object:
var d = new Date(document.getElementById("dt").value + "(GMT)");
The Date.parse() method is implementation-dependent, so it's possible to encounter inconsistencies when parsing a date string. In my browser (Chrome 47), I see different Date objects if the string to parse includes a space at the end:
d = new Date("2016-02-01")
Sun Jan 31 2016 17:00:00 GMT-0700 (Mountain Standard Time)
d = new Date("2016-02-01 ")
Mon Feb 01 2016 00:00:00 GMT-0700 (Mountain Standard Time)

Although i was not able to find the exact bug in my above code .... but i managed to partially solve the problem (Need to add code to validate month > 12 and change year if required )
dt = d.getDate();
dt++
dt = ('0' + dt).slice(-2);
mn = d.getMonth();
mn++;
mn = ('0' + mn).slice(-2);
yy = d.getFullYear();
var x = yy + "-" + mn + "-" + dt;
var y = new Date(yy, mn, 0);
dd = y.getDate();
if (dd < dt) {
console.log("in test.....");
mn++;
mn = ('0' + mn).slice(-2);
var x = yy + "-" + mn + "-" + '01';
console.log("test" + x);
}

Related

javascript create date from string and cast back to string

I am creating a date out of strings. I want my date to have the last hour and last minute of the given day. I have a calendar that is populating an input box with a date in the form 01-02-2020 (dd-mm-yyyy).
I want to add hours minutes and seconds to the date to make it look like this string: 2020-02-01 23:59:59.
I then want to sabtract x number of days from the date I've created to get a startdate.
My issue is that my date values are being somehow converted when I use the date functions. What I am doing is:
enddate = new Date(enddate);
enddate = enddate.setHours(23,59,59);
var startdate = new Date();
startdate.setDate( enddate.getDate() - 5);
I then want to concatenate my two dates to a string. Like ?startdate=2020-01-26 00:00:00&enddate=2020-02-01 23:59:59. Where the startdate has hours, minutes and seconds in the form 00:00:00 This string is what I ultimately want and it doesn't matter how I get to this start and enddate value. The steps above are just what I've tried. And actually the format of my dates in the the final string doesn't matter as long as it is something that sql can recognize and treat as a date.
How can I accomplish this?
Here is my full code:
enddate holds a date value in this form: 01-02-2020 (day month year european style)
datesplit = enddate.split("-");
enddate = new Date(datesplit[2],datesplit[0],datesplit[1]); //mm-dd-yyyy for US format
enddate.setHours(23);
enddate.setMinutes(59);
var startdate = new Date(enddate);
startdate.setDate(startdate.getDate() - daysback);
startdate.setHours(00);
startdate.setMinutes(00);
console.log("startdate and enddate: " + startdate + " - " + enddate)
//startdate and enddate: Tue Jan 28 2020 00:00:00 GMT-0500 (Eastern Standard Time) - Sun Feb 02 2020 23:59:00 GMT-0500 (Eastern Standard Time)
console.log("startdate and enddate date string: " + startdate.toISOString() + " - " + enddate.toISOString());
//startdate and enddate date string: 2020-01-27T05:00:00.000Z - 2020-02-03T04:59:00.000Z
Why the added time in the last console log value when the date is cast to ISO?? That last format is what I want, but value is different.
var st = "01-02-2020";
var pattern = /(\d{2})\-(\d{2})\-(\d{4})/;
var dt = new Date(st.replace(pattern,'$3-$2-$1'));
enddate = new Date(dt);
enddate.setHours(23,59,59);
var startdate = new Date(dt);
startdate.setHours(00,00,00);
startdate.setDate( startdate.getDate() - 5);
function js_yyyy_mm_dd_hh_mm_ss (mydate) {
now = new Date();
year = "" + mydate.getFullYear();
month = "" + (mydate.getMonth() + 1); if (month.length == 1) { month = "0" + month; }
day = "" + mydate.getDate(); if (day.length == 1) { day = "0" + day; }
hour = "" + mydate.getHours(); if (hour.length == 1) { hour = "0" + hour; }
minute = "" + mydate.getMinutes(); if (minute.length == 1) { minute = "0" + minute; }
second = "" + mydate.getSeconds(); if (second.length == 1) { second = "0" + second; }
return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}
var query = '?startdate='+js_yyyy_mm_dd_hh_mm_ss(startdate)+'&enddate='+js_yyyy_mm_dd_hh_mm_ss(enddate);
alert(query);
Well the problem basically was that you assign the same variable to different uses. I separate it (by adding 1 to the second one) and that solve it:
const enddate = '02-01-2020';
const daysback = 5;
datesplit = enddate.split("-");
enddate1 = new Date(datesplit[2],datesplit[0],datesplit[1]); //mm-dd-yyyy for US format
enddate1.setHours(23);
enddate1.setMinutes(59);
var startdate = new Date(enddate1);
startdate.setDate(startdate.getDate() - daysback);
startdate.setHours(00);
startdate.setMinutes(00);
console.log("startdate and enddate: " + startdate + " - " + enddate)
//startdate and enddate: Tue Jan 28 2020 00:00:00 GMT-0500 (Eastern Standard Time) - Sun Feb 02 2020 23:59:00 GMT-0500 (Eastern Standard Time)
console.log("startdate and enddate date string: " + startdate.toISOString() + " - " + enddate1.toISOString());
//startdate and enddate date string: 2020-01-27T05:00:00.000Z - 2020-02-03T04:59:00.000Z

How to convert a date with "nd","rd", "th" into a yyyy-mm-dd format Javasciript

I have an array of dates like:
dates=['2nd Oct 2014','20th Oct 2014','20th May 2019']
and I want to return them as an array in the YYYY-MM-DD format.
so far I have this:
function formatDate(dates) {
var t=[];
dates.map(function(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;
t.push([year, month, day].join('-'));
});
console.log(t);
return t;
}
var dates = ['2nd Oct 2014','20th Oct 2014','20th May 2019']
console.log(formatDate(dates));
but this gives me :
[NaN-NaN-NaN,NaN-NaN-NaN,NaN-NaN-NaN]
since its not able to recognize the date with "th", "nd".any idea how to fix this so that I get the o/p as:
[2014-10-02,2014-10-20,2019-05-20]
here is the fiddle: http://jsfiddle.net/nakpchvf/
Thanks!
If you're using moment, or if using it is an option, it's fairly simple:
const dates=['2nd Oct 2014','20th Oct 2014','20th May 2019'];
dates.forEach(date => {
console.log(moment(date, 'Do MMM YYYY').format('YYYY-MM-DD'));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
Just remove letters.
function formatDate(dates) {
var t=[];
dates.map(function(date){
let datePieces = date.split(' ');
datePieces[0] = datePieces[0].replace(/\D+/g, '');
var d = new Date(datePieces.join(' ')),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
t.push([year, month, day].join('-'));
});
return t;
}
var dates = ['2nd Oct 2014','20th Oct 2014','20th May 2019']
console.log(formatDate(dates));
Basically above I take each date and split it into 3 different parts. I then fix the first index (the one causing an issue) by removing any non-numerical characters. After that I can recombine to form your date string :).
Without any external library and nevertheless compact:
function formatDate(d) {
return new Date(d.replace(/^(\d+)\w+/,"$1")).toLocaleString().replace(/^(\d+)\/(\d+)\/(\d+),.*$/, "$3-$2-$1")
}
console.log(['2nd Oct 2014','20th Oct 2014','20th May 2019'].map(formatDate))
If you are willing to obtain the result without using any external library, you can try like this using the concept of regular expressions for replacement of st, nd, rd, th kind of substrings with '' (blank string) from date strings in array.
I have also used ternary operator ?: for applying an inline if-else to convert month/date like 1 to 01 etc.
I have also used map() method defined on arrays to skip the use of loop.
function formatDates(dates) {
return dates.map((date) => {
const d = new Date(date.replace(/(st)|(nd)|(rd)|(th)/ig, ""));
const yyyy = d.getFullYear();
const mm = "" + (d.getMonth() + 1);
const dd = "" + d.getDate();
return `${yyyy}-${mm.length === 1? "0" + mm: mm}-${dd.length === 1? "0" + dd: dd}` ;
})
}
var dates = ['2nd Oct 2014', '20th Oct 2014', '20th May 2019']
console.log(formatDates(dates)); // [ '2014-10-02', '2014-10-20', '2019-05-20' ]
Just use replace() function to replace these words with empty like this
function formatDate(dates) {
var t=[];
dates.map(function(date){
var words=["th","nd"];
for(var i=0;i<words.length;i++){
date=date.replace(words[i],"");
}
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;
t.push([year, month, day].join('-'));
});
console.log(t);
return t;
}
var dates = ['2nd Oct 2014','20th Oct 2014','20th May 2019']
console.log(formatDate(dates));

Javascript format date

I have a date string which coming from the db as follows
/Date(1469167371657)/
Is there any way to convert this date to following format using javascript
MM/DD/YYYY HH:MM
I've searched a lot but unble to find a solution
In plain javascript you have to write your own function for string format a date, for example for your string format:
var date = new Date(1469167371657);
function stringDate(date) {
var mm = date.getMonth()+1;
mm = (mm<10?"0"+mm:mm);
var dd = date.getDate();
dd = (dd<10?"0"+dd:dd);
var hh = date.getHours();
hh = (hh<10?"0"+hh:hh);
var min = date.getMinutes();
min = (min<10?"0"+min:min);
return mm+'/'+dd+'/'+date.getFullYear()+" "+hh+":"+min;
}
console.log(stringDate(date));
drier code version
var date = new Date(1469167371657);
function stringDate(date) {
return ("0" + (date.getMonth() + 1)).slice(-2)+'/'
+("0" + date.getDate()).slice(-2)+'/'
+date.getFullYear()+" "
+("0" + date.getHours()).slice(-2)+':'
+("0" + date.getMinutes()).slice(-2)
}
console.log(stringDate(date));
with pure js you can do the folowing
var d = new Date();
console.log(d.getMonth() + 1 + "/" + d.getDate() + "/" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes())
You can use - http://momentjs.com/ and have it done like:
moment(1469167371657).format('MM/DD/YYYY HH:MM')
You can do this with the following steps:
1) convert the timestamp to a date object.
var timestamp = "/Date(1469167371657)/"; // However you want to save whatever comes from your database
timestamp = timestamp.substr(timestamp.indexOf("(")+1); // gives 1469167371657)/
timestamp = timestamp.substr(0,timestamp.indexOf(")")); // gives 1469167371657
var d = new Date(timestamp);
2) set it to your format
function leadZero(i) {if(i < 10) {return "0"+i;} return i;} // Simple function to convert 5 to 05 e.g.
var time = leadZero(d.getMonth()+1)+"/"+leadZero(d.getDate())+"/"+d.getFullYear()+" "+leadZero(d.getHours())+":"+leadZero(d.getMinutes());
alert(time);
Note: the date / timestamp you provided is too high for javascript to understand, so this example will not work correclty
I believe that number is milliseconds so to convert it to date, you would do this:
var time = new Date().getTime();
var date = new Date(time);
alert(date.toString()); // Wed Jan 12 2011 12:42:46 GMT-0800 (PST)
var time=1469167371657;
var date = new Date(time);
alert(date.toString());

Convert UTC Date to dd/mm/yyyy Format

I am having some difficulties when trying to convert UTC Date format to dd/mm/yyyy in JavaScript:
var launchDate = attributes["launch_date"];
if (isBuffering) {
var date = new Date(launchDate);
var d = new Date(date.toLocaleDateString());
launchDate = ((d.getUTCMonth() + 1) + "/" + (d.getUTCDate() + 1) + "/" + (d.getUTCFullYear()));
}
I tried with this, but it returns me an invalid date. So I changed to this:
var launchDate = attributes["launch_date"];
if (isBuffering) {
var date = new Date(launchDate);
var d = formatDate(new Date(date.toLocaleDateString()));
launchDate = ((d.getUTCMonth() + 1) + "/" + (d.getUTCDate() + 1) + "/" + (d.getUTCFullYear()));
}
However, it still returning me invalid Date. I wonder is there any possible way to change the date format of Fri May 31 2013 17:41:01 GMT+0200 (CEST) to dd/mm/yyyy?
Thanks in advance.
var d = new Date();
var n = d.toLocaleDateString();
This will be more superior in build JS method!
function formatDate(d)
{
date = new Date(d)
var dd = date.getDate();
var mm = date.getMonth()+1;
var yyyy = date.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm};
return d = dd+'/'+mm+'/'+yyyy
}
Try it:
Date.parseExact(Your_Date, 'dd/MM/yyyy').toString('MM/dd/yyyy');
or
Date.parseExact(Your_Date, 'MM/dd/yyyy').toString('dd/MM/yyyy');
Month is 0 indexed, but day is not. You don't need to add 1 to your day.
Also, you're formatting it for MM/dd/yyyy, not dd/MM/yyyy.
solution:
var launchDate = attributes["launch_date"];
if (isBuffering) {
var date = new Date(launchDate);
var d = formatDate(new Date(date.toLocaleDateString()));
launchDate = ((d.getUTCDate())+ "/" + (d.getUTCMonth() + 1) + "/" + (d.getUTCFullYear()));
}

Parsing date and time from formatted date

I have a date in the following format:
Wed Jul 17 2013 13:00:00 GMT-0700 (PDT)
Can anyone tell me how to parse the date
Wed Jul 17 2013
and time out of this without using string functions
1:00pm
One of the simplest ways is to make sure your LOCALES are set properly, which allows you to do something like this:
var myStrDate = 'Wed Jul 17 2013 13:00:00 GMT-0700 (PDT)';
var myDate = Date.parse(myStrDate);
var myDateOnly = myDate.toLocaleDateString();
var myTimeOnly = myDate.toLocaleTimeString();
Here's a great place to start: http://www.w3schools.com/jsref/jsref_obj_date.asp
You can construct a Date object with the date string, combined with additional functions to get the required output. dayname() returns the dayname, monthname() returns the three-letter month name.
I've used console.info() for outputting results - alert() can be used as an alternative if appropriate.
function dayname(d)
{
var names = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri","Sat" ];
return names[d.getDay()];
}
function monthname(d)
{
var names = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
return names[d.getMonth()];
}
// construct new date object passing date string as parameter
var d = new Date("Wed Jul 17 2013 13:00:00 GMT-0700 (PDT)");
console.info(dayname(d) + ' ' + monthname(d) + ' ' + d.getDate() + ' ' + d.getFullYear());
For the time, this gettime() function checks the hour to output am or pm correctly, and for correct formatting-:
function gettime(d)
{
var ampm = "am";
var hour = d.getHours();
var mins = d.getMinutes();
if (hour >= 12)
{
hour = hour - 12;
ampm = "pm";
}
if (hours < 10)
hours = "0" + hours;
if (mins < 10)
mins = "0" + mins;
return hour + ":" + mins + ampm;
}
console.info(gettime(d));
var ms = Date.parse(new Date("Wed Jul 17 2013 13:00:00 GMT-0700 (PDT)"));
var curr_date = ms.getDate();
var curr_month = ms.getMonth() + 1; //Months are zero based
var curr_year = ms.getFullYear();
var hours = ms.getHours();
var mins = ms.getMinutes();
suf = (hours >= 12)? 'pm' : 'am';
hours = hours % 12;
document.write(curr_date + "-" + curr_month + "-" + curr_year + " " + hours + ":" + min + " " + suffix);
Also try using moment.js, you can format dateTime as you wish.
Here great reference to learn date functions in javascript https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Categories

Resources