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')
Related
This question already has answers here:
Convert a Unix timestamp to time in JavaScript
(34 answers)
How do I format a date in JavaScript?
(68 answers)
Closed last year.
How to convert this timestamp 1382086394000 to 2013-10-18 08:53:14 using a function in javascript? Currently I have this function:
function cleanDate(d) {return new Date(+d.replace(/\/Date\((\d+)\)\//, '$1'));}
The value 1382086394000 is probably a time value, which is the number of milliseconds since 1970-01-01T00:00:00Z. You can use it to create an ECMAScript Date object using the Date constructor:
var d = new Date(1382086394000);
How you convert that into something readable is up to you. Simply sending it to output should call the internal (and entirely implementation dependent) toString method* that usually prints the equivalent system time in a human readable form, e.g.
Fri Oct 18 2013 18:53:14 GMT+1000 (EST)
In ES5 there are some other built-in formatting options:
toDateString
toTimeString
toLocaleString
and so on. Note that most are implementation dependent and will be different in different browsers. If you want the same format across all browsers, you'll need to format the date yourself, e.g.:
alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());
* The format of Date.prototype.toString has been standardised in ECMAScript 2018. It might be a while before it's ubiquitous across all implementations, but at least the more common browsers support it now.
This works fine. Checked in chrome browser:
var theDate = new Date(timeStamp_value * 1000);
dateString = theDate.toGMTString();
alert(dateString );
why not simply
new Date (timestamp);
A date is a date, the formatting of it is a different matter.
Moment.js can convert unix timestamps into any custom format
In this case : var time = moment(1382086394000).format("DD-MM-YYYY h:mm:ss");
will print 18-10-2013 11:53:14;
Here's a plunker that demonstrates this.
Here are the simple ways to every date format confusions:
for current date:
var current_date=new Date();
to get the Timestamp of current date:
var timestamp=new Date().getTime();
to convert a particular Date into Timestamp:
var timestamp_formation=new Date('mm/dd/yyyy').getTime();
to convert timestamp into Date:
var timestamp=new Date('02/10/2016').getTime();
var todate=new Date(timestamp).getDate();
var tomonth=new Date(timestamp).getMonth()+1;
var toyear=new Date(timestamp).getFullYear();
var original_date=tomonth+'/'+todate+'/'+toyear;
OUTPUT:
02/10/2016
we need to create new function using JavaScript.
function unixTime(unixtime) {
var u = new Date(unixtime*1000);
return u.getUTCFullYear() +
'-' + ('0' + u.getUTCMonth()).slice(-2) +
'-' + ('0' + u.getUTCDate()).slice(-2) +
' ' + ('0' + u.getUTCHours()).slice(-2) +
':' + ('0' + u.getUTCMinutes()).slice(-2) +
':' + ('0' + u.getUTCSeconds()).slice(-2) +
'.' + (u.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5)
};
console.log(unixTime(1370001284))
2016-04-30 08:36:26.000
This is what I did for the Instagram API. converted timestamp with date method by multiplying by 1000.
and then added all entity individually like (year, months, etc)
created the custom month list name and mapped it with getMonth() method which returns the index of the month.
convertStampDate(unixtimestamp){
// Months array
var months_arr = ['January','February','March','April','May','June','July','August','September','October','November','December'];
// Convert timestamp to milliseconds
var date = new Date(unixtimestamp*1000);
// Year
var year = date.getFullYear();
// Month
var month = months_arr[date.getMonth()];
// Day
var day = date.getDate();
// Hours
var hours = date.getHours();
// Minutes
var minutes = "0" + date.getMinutes();
// Seconds
var seconds = "0" + date.getSeconds();
// Display date time in MM-dd-yyyy h:m:s format
var fulldate = month+' '+day+'-'+year+' '+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
// final date
var convdataTime = month+' '+day;
return convdataTime;
}
Call with stamp argument
convertStampDate('1382086394000')
and that's it.
Use .toLocaleString:
// undefined uses default locale
console.log(new Date().toLocaleString(undefined, {dateStyle: 'short'}));
Or custom method in case you don't want to use the toLocaleString for some reason:
formatDate is the function you can call it and pass the date you want to format to dd/mm/yyyy
var unformatedDate = new Date("2017-08-10 18:30:00");
$("#hello").append(formatDate(unformatedDate));
function formatDate(nowDate) {
return nowDate.getDate() +"/"+ (nowDate.getMonth() + 1) + '/'+ nowDate.getFullYear();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hello">
</div>
My ES6 variant produces a string like this 2020-04-05_16:39:45.85725. Feel free to modify the return statement to get the format that you need:
const getDateStringServ = timestamp => {
const plus0 = num => `0${num.toString()}`.slice(-2)
const d = new Date(timestamp)
const year = d.getFullYear()
const monthTmp = d.getMonth() + 1
const month = plus0(monthTmp)
const date = plus0(d.getDate())
const hour = plus0(d.getHours())
const minute = plus0(d.getMinutes())
const second = plus0(d.getSeconds())
const rest = timestamp.toString().slice(-5)
return `${year}-${month}-${date}_${hour}:${minute}:${second}.${rest}`
}
There is a simple way to convert to a more readable form
new Date().toLocaleString();
new Date(1630734254000).toLocaleString();
Outputs in this format => 9/4/2021, 11:14:14 AM
new Date(timestamp).toString().substring(4, 15)
1631685556789 ==> Sep 15 2021
To calculate date in timestamp from the given date
//To get the timestamp date from normal date: In format - 1560105000000
//input date can be in format : "2019-06-09T18:30:00.000Z"
this.calculateDateInTimestamp = function (inputDate) {
var date = new Date(inputDate);
return date.getTime();
}
output : 1560018600000
I am getting the date as
data.created = "Wed May 03 2017 15:41:49 GMT 0530(IST)"
I want to convert it to
regular isi format like
2017-03-12
My code,
var created = new Date(data.created);
created = created.toISOString()
Can anyone help me.Thanks.
You can use Date $filter to get the formatted string.
var formatedStr = $filter('date')(new Date(data.created),'yyyy-MM-dd');
Since your input is URL encoded, first you have to decodeURIComponent (which replaces things like %20 with spaces and so on).
Then convert the result into a Date object.
Then use the getFullYear, getMonth and getDate functions to get these data, but don't forget to pad it with 0 (for numbers lower than 10).
var input = "Wed%20May%2003%202017%2015:41:49%20GMT%200530%20(IST)";
function formatDate(d) {
var month = (d.getMonth() + 1)
, day = '' + d.getDate()
, year = d.getFullYear()
;
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
return [year, month, day].join('-');
}
var decoded = decodeURIComponent(input);
var inputDate = new Date(decoded);
var output = formatDate(inputDate);
console.log(output);
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.
This question already has answers here:
Convert a Unix timestamp to time in JavaScript
(34 answers)
How do I format a date in JavaScript?
(68 answers)
Closed last year.
How to convert this timestamp 1382086394000 to 2013-10-18 08:53:14 using a function in javascript? Currently I have this function:
function cleanDate(d) {return new Date(+d.replace(/\/Date\((\d+)\)\//, '$1'));}
The value 1382086394000 is probably a time value, which is the number of milliseconds since 1970-01-01T00:00:00Z. You can use it to create an ECMAScript Date object using the Date constructor:
var d = new Date(1382086394000);
How you convert that into something readable is up to you. Simply sending it to output should call the internal (and entirely implementation dependent) toString method* that usually prints the equivalent system time in a human readable form, e.g.
Fri Oct 18 2013 18:53:14 GMT+1000 (EST)
In ES5 there are some other built-in formatting options:
toDateString
toTimeString
toLocaleString
and so on. Note that most are implementation dependent and will be different in different browsers. If you want the same format across all browsers, you'll need to format the date yourself, e.g.:
alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());
* The format of Date.prototype.toString has been standardised in ECMAScript 2018. It might be a while before it's ubiquitous across all implementations, but at least the more common browsers support it now.
This works fine. Checked in chrome browser:
var theDate = new Date(timeStamp_value * 1000);
dateString = theDate.toGMTString();
alert(dateString );
why not simply
new Date (timestamp);
A date is a date, the formatting of it is a different matter.
Moment.js can convert unix timestamps into any custom format
In this case : var time = moment(1382086394000).format("DD-MM-YYYY h:mm:ss");
will print 18-10-2013 11:53:14;
Here's a plunker that demonstrates this.
Here are the simple ways to every date format confusions:
for current date:
var current_date=new Date();
to get the Timestamp of current date:
var timestamp=new Date().getTime();
to convert a particular Date into Timestamp:
var timestamp_formation=new Date('mm/dd/yyyy').getTime();
to convert timestamp into Date:
var timestamp=new Date('02/10/2016').getTime();
var todate=new Date(timestamp).getDate();
var tomonth=new Date(timestamp).getMonth()+1;
var toyear=new Date(timestamp).getFullYear();
var original_date=tomonth+'/'+todate+'/'+toyear;
OUTPUT:
02/10/2016
we need to create new function using JavaScript.
function unixTime(unixtime) {
var u = new Date(unixtime*1000);
return u.getUTCFullYear() +
'-' + ('0' + u.getUTCMonth()).slice(-2) +
'-' + ('0' + u.getUTCDate()).slice(-2) +
' ' + ('0' + u.getUTCHours()).slice(-2) +
':' + ('0' + u.getUTCMinutes()).slice(-2) +
':' + ('0' + u.getUTCSeconds()).slice(-2) +
'.' + (u.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5)
};
console.log(unixTime(1370001284))
2016-04-30 08:36:26.000
This is what I did for the Instagram API. converted timestamp with date method by multiplying by 1000.
and then added all entity individually like (year, months, etc)
created the custom month list name and mapped it with getMonth() method which returns the index of the month.
convertStampDate(unixtimestamp){
// Months array
var months_arr = ['January','February','March','April','May','June','July','August','September','October','November','December'];
// Convert timestamp to milliseconds
var date = new Date(unixtimestamp*1000);
// Year
var year = date.getFullYear();
// Month
var month = months_arr[date.getMonth()];
// Day
var day = date.getDate();
// Hours
var hours = date.getHours();
// Minutes
var minutes = "0" + date.getMinutes();
// Seconds
var seconds = "0" + date.getSeconds();
// Display date time in MM-dd-yyyy h:m:s format
var fulldate = month+' '+day+'-'+year+' '+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
// final date
var convdataTime = month+' '+day;
return convdataTime;
}
Call with stamp argument
convertStampDate('1382086394000')
and that's it.
Use .toLocaleString:
// undefined uses default locale
console.log(new Date().toLocaleString(undefined, {dateStyle: 'short'}));
Or custom method in case you don't want to use the toLocaleString for some reason:
formatDate is the function you can call it and pass the date you want to format to dd/mm/yyyy
var unformatedDate = new Date("2017-08-10 18:30:00");
$("#hello").append(formatDate(unformatedDate));
function formatDate(nowDate) {
return nowDate.getDate() +"/"+ (nowDate.getMonth() + 1) + '/'+ nowDate.getFullYear();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hello">
</div>
My ES6 variant produces a string like this 2020-04-05_16:39:45.85725. Feel free to modify the return statement to get the format that you need:
const getDateStringServ = timestamp => {
const plus0 = num => `0${num.toString()}`.slice(-2)
const d = new Date(timestamp)
const year = d.getFullYear()
const monthTmp = d.getMonth() + 1
const month = plus0(monthTmp)
const date = plus0(d.getDate())
const hour = plus0(d.getHours())
const minute = plus0(d.getMinutes())
const second = plus0(d.getSeconds())
const rest = timestamp.toString().slice(-5)
return `${year}-${month}-${date}_${hour}:${minute}:${second}.${rest}`
}
There is a simple way to convert to a more readable form
new Date().toLocaleString();
new Date(1630734254000).toLocaleString();
Outputs in this format => 9/4/2021, 11:14:14 AM
new Date(timestamp).toString().substring(4, 15)
1631685556789 ==> Sep 15 2021
To calculate date in timestamp from the given date
//To get the timestamp date from normal date: In format - 1560105000000
//input date can be in format : "2019-06-09T18:30:00.000Z"
this.calculateDateInTimestamp = function (inputDate) {
var date = new Date(inputDate);
return date.getTime();
}
output : 1560018600000
I need to check if the date is in the past. This is what I have so far. JSfiddle here.
var date = "09/12/2013";
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var todaysDate = +(('' + day).length < 2 ? '0' : '') + day + '/' + (('' + month).length < 2 ? '0' : '') + month + '/' + d.getFullYear();
if (date < todaysDate) {
alert("in the past");
} else {
alert("in the future");
}
Currently it is saying that the date was in the past, when it should be in the future. I know I need to parse the string as a date, but not sure how.
Help?
With that input format, you can't use a string comparison, because the least significant values are on the left. Note: I'm assuing that date is December 9th, 2013. If you're doing the American thing where it's September 12th, 2013, you'll have to adjust the indexes into parts below.
You could reverse the fields:
var date = "09/12/2013";
var parts = date.split('/');
date = parts[2] + "/" + parts[1] + "/" + parts[0];
...and then do your string comparison (being sure to construct the string for "today" in the same order — year/month/day).
If you're going to do that, you could go ahead and finish the job
var date = "09/12/2013";
var parts = date.split('/');
var date = new Date(parseInt(parts[2], 10), // year
parseInt(parts[1], 10) - 1, // month, starts with 0
parseInt(parts[0], 10)); // day
if (date < new Date()) {
// It's in the past, including one millisecond ago
}
...but of course, if you don't want the expression to be true for one millisecond ago, your string approach is fine.
var date = new Date("09/12/2013");
var d = new Date();
console.log(date>d); // true
var date = new Date("09/12/2011");
console.log(date>d); // false
JavaScript's native Date comparator only works on Date objects, whereas you are comparing Strings. You should parse date into a Date object, and then compare it with d.
//define parse(string) --> Date
if(parse(date) < new Date()) {
alert('past');
} else {
alert('future');
}