Javascript convert numbers into date - javascript

I am getting an input as in
23071996 being DDMMYYYY in date.
or
07231996 which is MMDDYYYY
Now I want to translate this input to a date to see if this date is valid or not.
From this question, I got how we can check if it is valid date or not but I am not sure how I can translate this to 23071996 or 07231996 to actual date

You can do this using substring().
Example:
var date = '23071996';
function convertDate(date) {
if(date.length !== 8) return 'Invalid Date'; // Checks if date is valid in terms of length
var day = date.substring(0, 2);
var month = date.substring(2, 4);
var year = date.substring(4, 8);
return { day: day, month: month, year: year };
}
var convertedDate = convertDate(date); // Converted date
function convertToDateObject(convertedDate) {
return new Date(convertedDate.year, convertedDate.month, convertedDate.day);
}
var trueDate = convertToDateObject(convertedDate); // Date as JavaScript object, this might be useful
Converting this to the American date format is relatively easy, you just swap the day and month. Accepting both formats would be quite difficult without getting input from the user on what format it is.

var _d = '07231996';
_d = _d.replace(/(\d{2})(\d{2})(\d{4})/, "$1-$2-$3");
document.write(new Date(_d));

Using Date() constructor and dateString format:
let str = '23071996';
date = new Date(str.slice(-4) + '-' + str.slice(2,4) + '-' + str.slice(0,2))
console.log(date)

Related

Compare a date in string format with todays date

I know this has been asked before but I can't get it to work due to my date format, which I can't change. Any help would be appreciated.
My date is in this format;
4/11/2017 12:30 PM.
If I inspect it in the developer tools it shows it as
4/11/2017 12:30 PM EDIT: Won't show with prepended space here
i.e. with a space in front, not sure if that's relevant.
Does anyone know if it's possible or how to compare it with today's date to see if it's in the past or future?
I've tried tinkering with the following code but can't get it to work because of the time, PM, and forward slashes.
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(d,m,y);
mydate=new Date('13/04/2017');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
If you have dates that are in the same format of something like 13/04/2017, you could split the string based on the slashes and compare the values starting from the right moving left.
By this, I mean when you have your array of three values for each date, you could first compare the year, if that's the same, move on to comparing the month, if that's the same then on to comparing the day.
But if for instance one of the year's is 2018 while the other is 2016, you would immediately know that the 2018 one comes later.
var st = "19/05/2019";
var st2 = "19/05/2019";
function provideLaterDate(date1, date2) {
var splitDateDate1 = date1.split("/").reverse();
var splitDateDate2 = date2.split("/").reverse();
var laterDate = false;
splitDateDate1.forEach(function(val, idx, arr) {
if ( laterDate === false ) {
if ( val > splitDateDate2[idx] ) {
laterDate = splitDateDate1;
} else if ( val < splitDateDate2[idx]) {
laterDate = splitDateDate2;
} else {
laterDate = "Both are the same";
}
}
});
if ( /\//.test(laterDate) ) {
return laterDate.reverse().join("/");
} else {
return laterDate;
}
}
To get rid of the "time pm" part, you could simply do something like:
// Assuming your date has a structure like this: 4/11/2017 12:30 PM.
var newDate = unformattedDate.split(" ")[0];
// This will separate your date string by spaces, and since there are no spaces until after the year in your date, the 0 index will give you the date minus the time and pm portion. Please pardon the not-consistent variable names.
The problem was with the way you were constructing date. Construct date like this var mydate = new Date(2017, 04, 03); and it works.
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(d, m, y);
var mydate = new Date(2017, 04, 03);
console.log(date);
console.log(mydate)
if (date > mydate) {
alert("greater");
}
else {
alert("smaller")
}
You can split the date. Be aware you should contruct your date as follows:
var date = new Date(y,m,d);
Means year first, then month and finally day, as you can see under https://www.w3schools.com/jsref/jsref_obj_date.asp
You can use the following code to perform what you want:
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(y,m,d);
newdate = '13/04/2017'
array = newdate.split('/');
var d1 = array[0]
var m1 = array[1]-1
var y1 = array[2]
mydate = new Date(y1,m1,d1);
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can always check the date created is correct by using the date.toString() function. Be aware 0=January for month as you can check under https://www.w3schools.com/jsref/jsref_getmonth.asp. That's why I added the -1 for var m1.
Problem:
It's not working because you are comparing a date with an Invalid date, it will always return false.
Explanation:
And the Invalid date comes from the line new Date('13/04/2017'), because 13 is expected to be a month number and not a day which is an invalid month, because the new Date(stringDate) will be treated as a local Date and not a UTC date by the browser, and it depends on which browser you are using.
You can see in the JavaScript Date Specification that:
parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
Demo:
So if we change new Date('13/04/2017') to new Date('04/13/2017') the code will work as expected:
var date = new Date();
var mydate = new Date('04/13/2017');
console.log(date);
console.log(mydate)
if (date > mydate) {
alert("greater");
} else {
alert("smaller")
}
if(date.getTime()>mydate.getTime()){
alert("greater");
}
else if (date.getTime()==mydate.getTime){
alert("simmilar");
else {alert("smaller");}

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 dd/mm/yyyy string into JavaScript Date object? [duplicate]

This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Closed 8 months ago.
How to convert a date in format 23/10/2015 into a
JavaScript Date format:
Fri Oct 23 2015 15:24:53 GMT+0530 (India Standard Time)
MM/DD/YYYY format
If you have the MM/DD/YYYY format which is default for JavaScript, you can simply pass your string to Date(string) constructor. It will parse it for you.
var dateString = "10/23/2015"; // Oct 23
var dateObject = new Date(dateString);
document.body.innerHTML = dateObject.toString();
DD/MM/YYYY format - manually
If you work with this format, then you can split the date in order to get day, month and year separately and then use it in another constructor - Date(year, month, day):
var dateString = "23/10/2015"; // Oct 23
var dateParts = dateString.split("/");
// month is 0-based, that's why we need dataParts[1] - 1
var dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);
document.body.innerHTML = dateObject.toString();
For more information, you can read article about Date at Mozilla Developer Network.
DD/MM/YYYY - using moment.js library
Alternatively, you can use moment.js library, which is probably the most popular library to parse and operate with date and time in JavaScript:
var dateString = "23/10/2015"; // Oct 23
var dateMomentObject = moment(dateString, "DD/MM/YYYY"); // 1st argument - string, 2nd argument - format
var dateObject = dateMomentObject.toDate(); // convert moment.js object to Date object
document.body.innerHTML = dateObject.toString();
<script src="https://momentjs.com/downloads/moment.min.js"></script>
In all three examples dateObject variable contains an object of type Date, which represents a moment in time and can be further converted to any string format.
Here's one I prepared earlier...
convertToDate(dateString) {
// Convert a "dd/MM/yyyy" string into a Date object
let d = dateString.split("/");
let dat = new Date(d[2] + '/' + d[1] + '/' + d[0]);
return dat;
}
var dateString = "23/10/2015"; // Oct 23
var newData = dateString.replace(/(\d+[/])(\d+[/])/, '$2$1');
var data = new Date(newData);
document.body.innerHTML = date.toString();ere
While most responses were tied to splitting strings or using native date methods, the two closely-related ones using RegEx (i.e., answer by [drgol] and comment by [Tomás Hugo Almeida]) are both instructive about the use of capturing groups. Their succinctness also helps illustrate the value of capturing and distinguishing that from matching - two related concepts that can confuse new RegEx users. This code block consolidates their 2 answers but see originals above: const origDate = '23/07/2020'; const newDate = origDate.replace(/(\d+[/])(\d+[/])/, '$2$1'); // newDate = '07/23/2020';
I found the default JS date formatting didn't work.
So I used toLocaleString with options
const event = new Date();
const options = { dateStyle: 'short' };
const date = event.toLocaleString('en', options);
to get: DD/MM/YYYY format
See docs for more formatting options: https://www.w3schools.com/jsref/jsref_tolocalestring.asp
Parsing a string to create another string that is then parsed by the built–in parser is not an efficient strategy, particularly when neither string is in a format supported by ECMA-262.
A more efficient strategy is to parse the string once and give the parts directly to the constructor, avoiding the second parse, e.g.
const parseDMY = s => {
let [d, m, y] = s.split(/\D/);
return new Date(y, m-1, d);
};
console.log(parseDMY('23/10/2015').toString());
Date.parse only supports the formats produced by:
Date.protoype.toString
Date.protoype.toISOString
Date.protoype.toUTCString
Parsing of any other format (including m/d/y) is implementation dependent.
Here is a way to transform a date string with a time of day to a date object. For example to convert "20/10/2020 18:11:25" ("DD/MM/YYYY HH:MI:SS" format) to a date object
function newUYDate(pDate) {
let dd = pDate.split("/")[0].padStart(2, "0");
let mm = pDate.split("/")[1].padStart(2, "0");
let yyyy = pDate.split("/")[2].split(" ")[0];
let hh = pDate.split("/")[2].split(" ")[1].split(":")[0].padStart(2, "0");
let mi = pDate.split("/")[2].split(" ")[1].split(":")[1].padStart(2, "0");
let secs = pDate.split("/")[2].split(" ")[1].split(":")[2].padStart(2, "0");
mm = (parseInt(mm) - 1).toString(); // January is 0
return new Date(yyyy, mm, dd, hh, mi, secs);
}
you can use this short function
// dateString: "15/06/2021"
const stringToDate = (dateString) => {
const [day, month, year] = dateString.split('/');
return new Date([month, day, year].join('/'));
};
document.body.innerHTML = stringToDate("15/06/2021").toString();
var date = new Date("enter your date");//2018-01-17 14:58:29.013
Just one line is enough no need to do any kind of split, join, etc.:
$scope.ssdate=date.toLocaleDateString();// mm/dd/yyyy format
<!DOCTYPE html>
<script>
dateString = "23/10/2015"; //23 Oct 2015
d = dateString.split("/");
x = d[1] + "/" + d[0] + "/" + d[2]; //"10/23/2015"
y = d[2] + "/" + d[1] + "/" + d[0]; //"2015/10/23"
alert(
new Date(x) + "\n\n" +
new Date(y) + "\n\n" +
new Date(dateString) + "\n" +
"");
</script>

Add a variable number to a date in Java script

I have read a few articles but nothing seems to the point. I have created a form that records a reservation date (when a user wants to reserve a game) and the number of days they hope to borrow it for. I want to add this to the reservation date to get the date the game must be returned by. I have wrapped up my code so far into a function so that I can call it using an onclick method. What should this code look like to work properly? Almost forgot - to make life hard my date is written like this YYYY-MM-DD
function ReturnDate(){
var reservation_begin = document.getElementById('reservation_start').value;
var loan_period = document.getElementById('requested_days').value;
var reservation_end = document.getElementById('return_date');
var dateResult = reservation_begin + loan_period;
return_date.value = dateResult;
}
USING the Suggestions made by Linus
I made the following alterations but had trouble with the formatting of the return date. e.g Setting the reservation date to 2015-01-03 gave me the result of 2015-0-32 for the return date
function ReturnDate(){
var reservation_begin = document.getElementById('reservation_start').value;
var loan_period = document.getElementById('requested_days').value;
var resDate = new Date(reservation_begin);
alert(resDate)
var period = loan_period;
var output = document.getElementById('return_date');
resDate.setDate(resDate.getDate() + period);
alert(period)
//return_date.value = resDate.getFullYear() + "-" + (resDate.getMonth() + 1) + "-" + resDate.getDate();
return_date.value = resDate.getFullYear() + "-" + resDate.getMonth() + "-" + (resDate.getDate() +1);
}
As mentioned dates could be a bit tricky to handle with js.
But to just add days to a date this could be a solution?
JSBIN: http://jsbin.com/lebonababi/1/edit?js,output
JS:
var resDate = new Date('2015-02-01');
var period = 6;
var output = "";
resDate.setDate(resDate.getDate() + period);
output = resDate.getFullYear() + "-" + (resDate.getMonth() + 1) + "-" + resDate.getDate();
alert(output);
EDIT:
Added a new JSBin which is more consistent with the original code.
JSBin: http://jsbin.com/guguzoxuyi/1/edit?js,output
HTML:
<input id="reservationStart" type="text" value="2015-03-01" />
<br />
<input id="requestedDays" type="text" value="14" />
<br />
<a id="calculateDate" href="javascript:;">Calculate Date</a>
<br /><br /><br />
Output:
<input id="calculatedDate" type="text" />
JS:
// Click event
document.getElementById('calculateDate').addEventListener('click', returnDate);
// Click function
function returnDate(){
var reservationStart = document.getElementById('reservationStart').value,
requestedDays = parseInt(document.getElementById('requestedDays').value),
targetDate = new Date(reservationStart),
formattedDate = "";
// Calculate date
targetDate.setDate(targetDate.getDate() + requestedDays);
// Format date
formattedDate = formatDate(targetDate);
// Output date
document.getElementById('calculatedDate').value = formattedDate;
}
// Format date (XXXX-XX-XX)
function formatDate(fullDate) {
var dateYear = fullDate.getFullYear(),
dateMonth = fullDate.getMonth()+1,
dateDays = fullDate.getDate();
// Pad month and days
dateMonth = pad(dateMonth);
dateDays = pad(dateDays);
return dateYear + "-" + dateMonth + "-" + dateDays;
}
// Pad number
function pad(num) {
return (num < 10 ? '0' : '') + num;
}
As per my comment,
Split reservation_begin and use the Date constructor feeding in the
parts to create a Javascript date object. getTime will give you the
milliseconds since the Epoch. There are 86400000 milliseconds in a day, so
multiply this by loan_period. Add the two millisecond result together
and use the Date constructor with your total milliseconds to get
dateResult as a Javascript date object.
using Date.UTC but you don't have to.
function pad(num) {
return num < 10 ? '0' + num : num;
}
var reservation_begin = ('2015-02-01').split('-'),
loan_period = '5',
begin,
end;
reservation_begin[1] -= 1;
begin = new Date(Date.UTC.apply(null, reservation_begin)).getTime();
end = new Date(begin + 86400000 * loan_period);
document.body.textContent = [
end.getUTCFullYear(),
pad(end.getUTCMonth() + 1),
pad(end.getUTCDate())
].join('-');
Why split the date string into parts? This is to avoid cross browser parsing issues.
Why use milliseconds? This is the smallest value represented by Javascript Date, using this will avoid any rollover issues that may be present in browsers.
Why use UTC? You haven't specified the requirements for your script, and this is about as complex as it gets. You don't have to use it, you can just feed the parts into Date and use the non UTC get methods.
What does pad do? It formats the month values to MM and date values to DD.
Note that month is zero referenced in Javascript so months are represent by the numbers 0-11.
A bit confused with the third variable "reservation_end" but according to your question this solution might work.
var dateResult = new Date(reservation_begin);
dateResult.setDate(dateResult.getDate() + parseInt(loan_period));
alert(dateResult);
http://jsfiddle.net/uwfpbzt2/
Example using todays date:
var today = new Date();
today.setDate(today.getDate() + x);
where x is the number of days. Then just use getYear(), getMonth() and getDate() and format it how you like.
EDIT
var myDate = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Assuming your date is entered in dd/mm/yyyy format as inputDate then
dateParts = inputDate.split("/");
var myDate = new Date(dateParts[2], dateParts[1]-1, dateParts[0]);
Depending on the date format your split() delimiter and array positions may be different but this is the general idea.

How to convert javascript string format to date

In my ajax success I am getting result.Date as "/Date(-2208967200000)/". I need to check with the following date and proceed..
How to convert the "/Date(-2208967200000)/" to "01-01-1900" for below if condition?
if (result.Date != "01-01-1900") {
....
}
You can convert result.Date into you comparison date format, same as below example
var dateString = "\/Date(-2208967200000)\/".substr(6);
var currentTime = new Date(parseInt(dateString ));
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var date = day + "/" + month + "/" + year;
After doing this.. you can compare it with other date..
Reference
var jsonDate = "/Date(-2208967200000)/";
var date = new Date(parseInt(jsonDate.substr(6)));
alert(date);
The substr function takes out the "/Date(" part, and the parseInt function gets the integer and ignores the ")/" at the end. The resulting number is passed into the Date constructor.
jQuery dateFormat is a separate plugin. You need to load that explicitly using a tag.
You could use a regex to get the value between the brackets and then pass that to the Date():
var input = "/Date(-2208967200000)/";
var matches = /\(([^)]+)\)/.exec(input);
var date = new Date(parseInt(matches[1], 10));
Example fiddle

Categories