Compare to dates Javascript? [duplicate] - javascript

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Compare 2 dates with JavaScript
Hi,
I'm working on form validation for my application and i want to know where i would be to start looking at to find date comparison eg a start date and an end date. The dates inputted in to my application are in the form: DD/MM/YYYY.
Thanks in Advance,
Dean

If you are using the Javascript Date object, you can simply do:
var startDate = new Date();
var endDate = getEndDate();
if (endDate < startDate)
alert("Houston, we've got a problem!");
EDIT: Changed naming a bit just to stick to camelCase convention, even though I despise it.

this function lets you convert dates to timestamps with wich you could work:
http://caioariede.com/arquivos/strtotime.js

First, you'll want to parse the text into Date objects, then use the language's built-in date comparison. For example:
var dateStr = document.getElementById('foo').value;
var date = Date.parse(dateStr);
var dateStr2 = document.getElementById('foo2').value;
var date2 = Date.parse(dateStr2);
if (date < date2) {
// ...
}

Related

The problem of getting and working with dates in Js [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 5 months ago.
When working with the task, it became necessary to get dates from html, and to find out the time difference between them:
var now_time_div = document.getElementById("time_now_of");
var start_time_div = document.getElementById("time_when_start_of");
var time_now = now_time_div.textContent || now_time_div.innerHTML;
var time_start = start_time_div.textContent || start_time_div.innerHTML;
After that, without thinking about the format of the data, I wanted to find the time difference in ms:
var worked_time = time_now - time_start
That didn't work, because we are working with a string.
After entering the directory, I found the Date.parse() function, which returns the amount of time that has passed since the given date:
var worked_time = Date.parse(time_start);
but it turned out that it works only with a correctly submitted strig, for example
We need to have:
Date.parse('01 Jan 1970 00:00:00 GMT');
We have:
Date.parse('21.09.2022, 15:34:21')
Maybe someone knows an easy way to implement this without rebuilding the string?
If you don't want to bring in a library like moment.js, you can just massage the date string a bit so it can be parsed correctly
const dateString = '21.09.2022, 15:34:21';
const curDate = dateString.split(',')[0].substring(0, 10).split('.');
const curTime = dateString.split(',')[1];
const parsed = `${curDate[1]}'/'${curDate[0]}'/'${curDate[2]} ${curTime}`;
console.log(new Date(parsed).toString()); // Properly formatted date
You can used this parsed variable to compare to other properly formatted dates
You can use moment.js to parse custom date formats just as in for example Java:
https://momentjs.com/docs/#/parsing/string-format/
After that you can simply convert it to a js date using the toDate function: https://momentjs.com/docs/#/displaying/as-javascript-date/
Edit Example:
var mDate = moment('2022-09-21 10:15:00', 'YYYY-MM-DD HH:mm:ss');
var jsDate = mDate.toDate();

How to parse the date string in YYYY-MM-DD format [duplicate]

This question already has answers here:
Format JavaScript date as yyyy-mm-dd
(50 answers)
Closed 2 years ago.
I have date string in the format '2020/02/25 23:58:08' . I want to parse it to '2020-02-25".
Note : Initially date is in string format, after conversion whether it is in date or string format it doesn't matter.
file.js
function test (filepath) {
let date = "2020/02/25 23:58:08";
date = date.replace("//"/gi,"-");
// I am not familiar with regular expressions, I want to omit the data related to hours, seconds extra
}
When I ran the program, I gotUncaught ReferenceError: gi is not defined, gi is to globally replace
Try this
let date = "2020/02/25 23:58:08";
var date2 = new Date(date)
console.log(date2.toISOString().slice(0,10))
let date = `2020/02/25 23:58:08`;
let parsedDate = date.split(" ")[0].replace(/\//gi,'-');
console.log(parsedDate);
There is an error in the line using regex, should be:
let date = "2020/02/25 23:58:08";
date = date.replace(/\//gi,"-");
Then to get only the date, you can get the first 10 characters:
date.slice(0,10)
Final code:
let date = "2020/02/25 23:58:08";
date = date.replace(/\//gi,"-");
date.slice(0,10)
Although there are other ways to do it, you can use a library like momentJs which includes methods for this, like moment.format, it gives so many possibilities. But if you have a small case this is fine.

Custom Javascript Variable in GTM to convert date (string) to date [duplicate]

This question already has answers here:
How to parse a date in format "YYYYmmdd" in JavaScript?
(6 answers)
Closed 6 years ago.
I am pulling a date of birth as a string from a form on a website im looking after. I need to be able to derive an age from that date string.
My thoughts are converting it into a proper date using a split (its delimited by "%2F") and calculating from that but my syntax isnt that good so im having real trouble.
The code im working with to pull the string I need is;
function() {
var inputField = document.getElementById("date-of-birth-input");
return inputField.value || "";
}
Any help would be appreciated.
If you have the user input the date in a format like 1/1/1990, you could do something like this:
var inputField = document.getElementById("date-of-birth-input"); // `1/1/1990`
var today = new Date().getFullYear();
var birthdate = new Date(inputField).getFullYear();
var age = today - birthdate;
The JavaScript Date constructor is pretty flexible in what it can turn into a date, so you might not need to go through splitting-string hassles. Check out the docs.
Date format varies in different countries. In US the date format is MM-DD-YYYY while in Asian countries the date format is DD-MM-YYYY and in China its 'YYYY-MM-DD'. The right way to go about dealing with dates is using Moment.js
If you have a simple application/website include moment in your <head> tag as follows
<script src="moment.js"></script>
(Hoping you have downloaded moment.js and kept in the same structure as index.html). Otherwise use this if you want to use it directly from the net without downloading.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/locale/af.js"></script>
Then use the following
function() {
/* First-make sure you format moment according to your giving locale.
I'm formating here according to the US date format */
var inputField = moment(document.getElementById("date-of-birth-input")).format("MM-DD-YYYY");
return moment().diff(inputField, 'years');
}
I hope this helps. Thanks.

how to convert a date string '13.04.2015' into JavaScript Date object [duplicate]

This question already has answers here:
jquery/javascript convert date string to date
(6 answers)
Closed 6 years ago.
how can I convert a date string
'13.04.2015'
into JavaScript Date object in a performant way?
Try this parser:
var dateString = '13.04.2015';
var myDate = new Date(dateString.split('.').reverse());
Check the demo.
new Date( "13.04.2015".replace( /(\d{2}).(\d{2}).(\d{4})/, "$2/$1/$3") );
JSFiddle
Try this code:
var str = '13.04.2015',
dateParts = str.split('.'),
year = dateParts[2],
month = dateParts[1],
day = dateParts[0],
yourDate = new Date([year, month, day]);
JSFiddle example
Also if need to work a lot with dates, I would recomend you MomentJs Library
Code with it will look like:
moment('13.04.2015', 'DD.MM.YYYY')
JSFiddle example moment

Date restrictions on user input in JavaScript

I am trying to have a date entry box which has the following restrictions. Date must be today's date or earlier, but not more than 1 year previous. I have the following line:
if (myFDGDT - todayDate > 0 || (myFDGDT - todayDate)/86400000 < -365)
The first portion of that creates the appropriate alert when some enters a date after today's date. Not sure about the best way to cap the entry to a year previous. Attempted a few items, but the above was just an example of my last attempt. This is also written in a dependency and not in the Global JavaScript of our entry client.
Here is a snippet that will generate a Date object that is one year ago. You can compare against it as needed using greater than/less than operators.
var oneyear = new Date('01/01/1971'); // from unix epoch
var now = new Date();
var oneyearago = new Date(now - oneyear);
alert(oneyearago);
If you are manipulating dates a lot in your app you should consider using the momentjs library. For your problem the solution would be something like:
var momentdate = moment(date);
if (momentdate.isAfter(momentdate.add(1, 'year') ||
momentdate.isBefore(momentdate.startOf('day')) {
// Invalid date?
}
Hope this helps.

Categories

Resources