Convert string to date and compare two dates in javascript - javascript

I get a date in a variable in string format in javascript. It is like 26-02-2015.
Then I get today's date in another variable using new Date(). This gives me a long string like Mon Feb 23 2015 10:56:23 GMT+0530 (India Standard Time)
How can I compare these two date? I want to check which date is bigger.
This is what I am doing
var date = objParam[0].value;
var todaysDate = new Date();
if (date > todaysDate)
alert("Please select the valid date");

Use it like this:
date = new Date();
dateNew = (date.getDate()).toString() + "-" +
(date.getMonth() + 1).toString() + "-" +
(date.getFullYear()).toString();
dateNew contains the string with the format you mentioned. Now you can compare the two strings.

var d1='26-02-2015';
d1=d1.split('-');
var parsedDate=d1[1]+'/'+d1[0]+'/'+d1[2];
if(Date.now() > new Date(parsedDate).getTime()){
alert('past date')
} else {
alert('future date');
}

Related

Javascript date conversion and adding days

I have a date in the form of a string like below:
var dateInput= "Sat Dec 7 2019 00:00:00 GMT+0300 (East Africa Time)";
I want to convert this date to dd/mm/yyyy and be able to add and subtract days from this date and still retain the same format.
Here's what I did to convert this string to dd/mm/yyyy date format:
I used this helper function:
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');
}
So, then I did :
var date = new Date(convertDate(eddFromCouch));
which gave me the string 7/12/2019;
Then, when I tried to add the 5 days to the date above, I got the following:
date = date.setDate(date.getDate() + 5);
console.log(date); // returns 1563310800000
I believe 1563310800000 a UNIX timestamp which converts to July,16,2019
I was expecting it to return 12/12/2019.
Here is how you can achieve this using Moment.js. This library makes tasks like parsing, manipulating and displaying dates much easier to achieve.
var input = "2019-08-14T08:06:49.288Z";
var date = moment(input);
date.add(5, "days");
console.log(date.format("DD/MM/YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Your dateInput is actually the format returned by date.toString, and can be passed directly to the date constructor to get a date object.
function toDDMMYYY(date) {
let parts = [];
let dd = date.getDate();
let mm = date.getMonth() + 1;
let yyyy = date.getFullYear();
if (dd < 10) {
parts.push(`0${dd}`)
} else {
parts.push(`${dd}`)
}
if (mm < 10) {
parts.push(`0${mm}`)
} else {
parts.push(`${mm}`)
}
parts.push(yyyy)
return parts.join('/');
}
const input = "Sat Dec 7 2019 00:00:00 GMT+0300 (East Africa Time)";
let date = new Date(input);
date = new Date(date.setDate(date.getDate() + 5));
console.log(toDDMMYYY(date))

copy a date object from a user entered date

I am trying to put together a mostly automated form. I have the get current date fine but I am having problems collecting information from a user enter date to place it in another part of the form as well + 1 year. I.E. D.O.B = 08/06/2016 farther down the form expires 08/06/2017. I can make the current date enter automatically but when i try and get the date entered from the user nothing fills the lower date. I tried getting the date using document.getElementById('dob')
function datePone()
{
var date = new Date();
var day = date.getDate(document.getElementById('dob'))
var month = date.getMonth(document.getElementById('dob')) + 1;
var year = date.getFullYear(document.getElementById('dob')) + 1;
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var oneYear = year + "-" + month + "-" + day;
document.getElementById("dateOneYear").value = oneYear;
}
I've tried using set date or making a new var using document.getElementById('dob') but nothing i have tried has worked so far.
Since "dob" is an input field, to the get the entered data you need to use value property, so try
document.getElementById('dob').value
Also I suggest using momentjs library to manipulate with dates.
Where you have:
var day = date.getDate(document.getElementById('dob'))
the getDate method does not take any arguments, so they are ignored and the above is equivalent to:
var day = date.getDate()
You don't specify what format you're using for the string, "08/06/2016" is ambiguous. Does it represent 8 June or August 6?
You should not use the Date constructor or Date.parse to parse date strings, write your own small function or use a library. Also, adding one year to a date like 29 Feb 2016 will end up on 1 March 2017, so you need to apply a rule to accept that or change it to 28 Feb 2017.
Anyhow, assuming the input is in the format dd/mm/yyyy and you want the output date in the format yyyy-mm-dd, you can use a library or small functions like the following:
// Parse string in d/m/y format
// If invalid, return invalid Date
function parseDMY(s){
var b = s.split(/\D/);
var d = new Date(b[2], --b[1], b[0]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
// Return date string in yyyy-mm-dd format
function toISODate(d) {
return d.getFullYear() + '-' +
('0' + (d.getMonth()+1)).slice(-2) + '-' +
('0' + d.getDate()).slice(-2);
}
// Parse string to Date
var d = parseDMY('06/08/2016');
// Add one year
d.setFullYear(d.getFullYear() + 1);
console.log(toISODate(d));
Using a library like fecha.js, you'd parse the string using:
var d = fecha.parse('06/08/2016','DD/MM/YYYY');
and format the output:
fecha.format(d, 'YYYY-MM-DD')

How to convert timestamp to readable date/time?

I have an API result giving out timestamp like this 1447804800000. How do I convert this to a readable format using Javascript/jQuery?
You can convert this to a readable date using new Date() method
if you have a specific date stamp, you can get the corresponding date time format by the following method
var date = new Date(timeStamp);
in your case
var date = new Date(1447804800000);
this will return
Wed Nov 18 2015 05:30:00 GMT+0530 (India Standard Time)
Call This function and pass your date :
JS :
function getDateFormat(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;
var date = new Date();
date.toLocaleDateString();
return [day, month, year].join('-');
}
;
In my case, the REST API returned timestamp with decimal. Below code snippet example worked for me.
var ts= 1551246342.000100; // say this is the format for decimal timestamp.
var dt = new Date(ts * 1000);
alert(dt.toLocaleString()); // 2/27/2019, 12:45:42 AM this for displayed

Getting date from string with specific format

I have a date at a string - dtStr
var dtStr = "Thu May 28 02:13:16 BDT 2015";
I want to get a date like - MM DD YYYY HH mm format from the dtStr. For getting this I am trying to convert the dtStr to a Date and then try to use date format like this -
var dtStr = "Thu May 28 02:13:16 BDT 2015";
today = new Date(dtStr);
alert( today.toLocalDateFormat("MM DD YYYY HH mm") );
But it didn't work for me. Can any one help me for - converting dtStr to a date with format MM DD YYYY HH mm ?
Thanks in advance.
Unfortunately, the string you're trying to parse won't be accepted by Date.parse(), the method that will parse the string when you're creating it. If the string will always be in that format, you could do some string manipulation and rearrange it to the RFC2822/IETF format, which Date() can handle.
// this creates a proper Date object
new Date("Thu, May 28 2015 02:13:16 +0600");
Alternatively, you could create a new Date object with one of the other constructors, by splitting/parsing the string yourself, and inserting them in the correct places in the constructor.
At this point, you'll have a Date object, but you still need to get the values from it - the only built in method that can do something like what you're trying to do is toLocaleFormat(), which isn't standard track (it's not supported in my version of Chrome, for example). Thus, you would need to get the values independently, and concatenate them together.
At this point, it's probably easier to just do straight up parsing of the string, and skip the Date object altogether, or use a library like datejs, which provides support for formatting output strings.
You may try to use the following method -
function formatReview(date){
/*****************************************************************
* The method parameter 'date' is in the following format -
* "Thu May 28 02:13:16 BDT 2015"
* Javascript 'new Date()' has not suitable constructor to
* support this format. The parameter 'date' need to
* convert to fee the Date() constructor.
*******************************************************************/
var monthSymbols = "JanFebMarAprMayJunJulAugSepOctNovDec";
var elements = date.split(" ");
var day = elements[0];
var monthName = elements[1];
var monthIndex = monthSymbols.indexOf(monthName)/3 +1;
var date = elements[2];
var year = elements[5];
var timestamp = elements[3];
var timestampElements = timestamp.split(":");
var hour = timestampElements[0];
var minutes = timestampElements[1];
var dateString = monthIndex +"-"+ date +"-"+ year +" "+ hour +":"+ minutes;
return dateString;
}
Try this
var todayDate=new Date("Thu May 29 2014 13:50:00");
var format ="AM";
var hour=todayDate.getHours();
var min=todayDate.getMinutes();
if(hour>11){format="PM";}
if (hour > 12) { hour = hour - 12; }
if (hour == 0) { hour = 12; }
if (min < 10){min = "0" + min;}
document.write(todayDate.getMonth()+1 + " / " + todayDate.getDate() + " / " + todayDate.getFullYear()+" "+hour+":"+min+" ");
fiddle: http://jsfiddle.net/e0ejguju/

Change the date format my identifying the date and month?

function date()
{
var myDate=new Date(document.getElementById('date').value); //get the date from a textfield
var day=myDate.getDate();
var month=myDate.getMonth()+1;
var yr=myDate.getFullYear();
if(dateformat=="dd/mm/yyyy") //checking the date format //
{
document.getElementById('date').value=day + "/" + month + "/" + yr;
}
else
{
document.getElementById('date').value=month+"/"+day + "/" +yr;
}
}
This function onchange is written in onchange mehod of textbox date,on changing the textfield it should change the date format that is set by default.
If dd/mm/yyy is the format then change it in that format and if mm/dd/yyy then change in this format.My code does the changes, but it cannot recognize which is the month!
For example.. if the date format is mm/dd/yyy and I type the date as 11/01/2001' (NOV -1 2001) it changes to01/11/2011` which should not be done.
But if I type 01-11-2001 (jan 1 2001) which is entered is correct ,but it changes to 11/01/2001
How can I change the code to correct this??? plz help!!!
Demo Fiddle
Javascript Code
function dateChange() {
var e = document.getElementById("dateformat");
var dateformat = e.options[e.selectedIndex].text;
var myDate;
if (dateformat == "dd/mm/yyyy") //checking the date format //
{
var value = document.getElementById('date').value;
var format = value.split("/");
myDate = new Date(format[2], format[1] - 1, format[0]);
var day = myDate.getDate();
var month = myDate.getMonth() + 1;
var yr = myDate.getFullYear();
document.getElementById('date').value = day + "/" + month + "/" + yr;
} else {
myDate = new Date(document.getElementById('date').value);
var day = myDate.getDate();
var month = myDate.getMonth() + 1;
var yr = myDate.getFullYear();
document.getElementById('date').value = month + "/" + day + "/" + yr;
}
document.getElementById('dateStr').innerHTML = myDate.toDateString();
}
Enter the date 01/02/2014 with mm/dd/yyyy in drop down the date would be Thu Jan 02 2014, now just change the drop down to dd/mm/yyyy the date would be Sat Feb 01 2014
Instantiating Javascript's Date object require this format new Date(yyyy,mm,dd), so when you use dd/mm/yyyy you need to manually ex-change the dd & mm values...
Reference
I guess the problem is that you either don't have dateformat specified or you compare it wrong.
if(dateformat=="dd/mm/yyyy")
If that always returns false, you will always get the second option.
Make sure dateformat is visible in the date() function, and make sure it actually gets the value you want it to have.
Secondly - the new Date() function actually parses the date before you check for the date format. I think you might want to do it the other way around: parse the input date, check which format it is in, and then output the result.

Categories