Change the date format my identifying the date and month? - javascript

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.

Related

How to manipulate a date that is fetched from an html input with javascript

I am trying to get a date from an html input to javascript, substract 3 years from it and then place the new date back into another html date input field.
I got the substraction to work with the current date but I can not get it to work when I fetch a date from an html input.
Below my code that works:
<input id="InputDate" data-role="datepicker"/>
<input id="OutputDate" data-role="datepicker"/>
<script type="text/javascript">
var dt = new Date(); // this line I want to replace with the next 2 lines!
//var inDate= document.getElementById("InputDate").value;
//var dt = new Date(inDate);
dt.setFullYear(dt.getFullYear() - 3);
var datestring = ("0" + dt.getDate()).slice(-2) + "." + ("0"+(dt.getMonth()+1)).slice(-2) + "." + dt.getFullYear();
document.getElementById("OutputDate").value = datestring;
When I fetch a date from the input field I get 'aN.aN.NaN' back into the output field.
I have tried document.getElementById("InputDate").valueAsDate instead, but this did not work either.
When I place an alert(dt) after the instantiation of dt I get 'Invalid Date'.
Any suggenstions how to get the fetched date in the DateObject correctly?
Regards, Manu
Just need to pass correct format to date() function:
//var dt = new Date(); // this line I want to replace with the next 2 lines!
var inDate= document.getElementById("InputDate").value;
inDate = inDate.split(".");
var dt = new Date(inDate[2],inDate[1],inDate[0]);
//alert(dt);
dt.setFullYear(dt.getFullYear() - 3);
var datestring = ("0" + dt.getDate()).slice(-2) + "." + ("0"+(dt.getMonth()+1)).slice(-2) + "." + dt.getFullYear();
document.getElementById("OutputDate").value = datestring;
<input id="InputDate" data-role="datepicker" value="19.05.2015"/>
<input id="OutputDate" data-role="datepicker"/>
var inputValues = document.getElementById("InputDate").value.split(".");
var dt = new Date(inputValues[2], inputValues[1] - 1, inputValues[0]);
If you get something like 22.12.1985 as InputDate value
first verify your ,document.getElementById("InputDate").value; is
returning correct date
var inDate= document.getElementById("InputDate").value;
var dt = new Date(Date.parse(inDate)); //use parse input to corret date format
dt.setFullYear(dt.getFullYear() - 3);
Use date format
var date = "2017-06-19";//yyyy-mm-dd or mm-dd-yyyy
var dt = new Date(date);
console.log(dt);
//output Mon Jun 19 2017 00:00:00 GMT+0545 (Nepal Standard Time)
// if you want to set the date to new output text box
var newDate = dt.getFullYear() + "-" + (dt.getMonth() + 1) + "-" + dt.getDate();
console.log(newDate);
var d = document;
d.g = d.getElementById;
var inDate = d.g("InputDate");
var outDate = d.g("OutputDate");
var datestring = "";
var mo = "";
var dt = null;
inDate.onchange = function() {
dt = new Date(inDate.value);
dt.setFullYear(dt.getFullYear() - 3);
datestring = ("0" + (dt.getMonth() + 1)).slice(-2) + "." + ("0" + dt.getDate()).slice(-2) + "." + dt.getFullYear();
outDate.value = datestring;
};
<input id="InputDate" data-role="datepicker" value="mm.dd.yyyy"><input id="OutputDate" data-role="datepicker" />
This revision makes use of the onchange event attribute which avoids the "NaN" message displaying in response to the default value of "mm.dd.yyyy" which serves as a prompt for the user. It also uses some short-cuts to reduce the verbosity of the code. Note: while the official example elegantly splits on a "." to get the date values, taking the time to use the Date methods to extract the month, day and year has an advantage despite the extra code. Splitting on a "." works as long as the input data contains a period to demarcate the month, day and year values. But the user could instead use a "/" or a "-" and then that splitting code would not yield the correct result, unless there was code that checked for the period.

How to convert isi date to iso in js

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);

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 can I format a json date in dd/mm/yy format in javascript?

I have a json date like \/Date(1334514600000)\/ in my response and when I convert it in javascript then I got this date Tue Apr 17 2012 11:37:10 GMT+0530 (India Standard Time),
but I need the date format like 17/04/2012 and I fail every time. Can anyone tell me how can I resolve it?
I don't think that the other posted answers are quite right, you have already accepted one as working for you so I won't edit it.
Here is an updated version of your accepted answer.
var dateString = "\/Date(1334514600000)\/".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;
alert(date);
It uses a technique from this answer to extract the epoch from the JSON date.
I found very helpful the row1 answer, however i got stuck on the format for input type="date" as only returns one string for decimals under 10, I was able to modify to work on input type="date", I basically adapted the code from row1 to the code from the link http://venkatbaggu.com/convert-json-date-to-date-format-in-jquery/
I was able through jquery .val add the date to the input
var dateString = "\/Date(1334514600000)\/".substr(6);
var currentTime = new Date(parseInt(dateString));
var month = ("0" + (currentTime.getMonth() + 1)).slice(-2);
var day = ("0" + currentTime.getDate()).slice(-2);
var year = currentTime.getFullYear();
var date = year + '-' + month + '-' + day;
alert(date);
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
var date = day + "/" + month + "/" + year
alert(date);
It's answer to your question...
Build the date object with your timestamp
var currentTime = new Date(1334514600000)
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
var date = day + "/" + month + "/" + year
alert(date);​
it works
http://jsfiddle.net/ChgUa/
//parse JSON formatted date to javascript date object
var bdate = new Date(parseInt(emp.Birthdate.substr(6)));
//format display date (e.g. 04/10/2012)
var displayDate = $.datepicker.formatDate("mm/dd/yy", bdate);
Easiest way of formatting date is by using pipes if you are using Angular.
Click here
//in .ts file
ngOnInit() {
this.currentDate = new Date()
}
//in html file
<p>Current date is:</p>{{currentDate | date: 'dd/MM/yyyy'}}
//Output: 22/04/2020
Here is an updated version of your accepted answer. DD/MM/YYYY Format Get Try This..
var dateString = "/Date(1623781800000+0530)/"+.substr(6);
var currentTime = new Date(parseInt(dateString));
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
if (month.toString().length == 1)
month = "0" + month.toString();
if (day.toString().length == 1){
day = "0" + currentTime.getDate();}
var datenew = day + "/" + month + "/" + year;
var Date = new Date(Tue Jun 15 2021 23:52:47 GMT+0800 (Malaysia Time)).toDateString(); console.log(Date);
Result == Tue Jun 15 2021

Add days to date using Javascript

I am trying to add days to a given date using Javascript. I have the following code:
function onChange(e) {
var datepicker = $("#DatePicker").val();
alert(datepicker);
var joindate = new Date(datepicker);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}
On first alert I get the date 24/06/2011 but on second alert I get Thu Dec 06 2012 00:00:00 GMT+0500 (Pakistan Standard Time) which is wrong I want it to remain 24/06/2011 so that I can add days to it. In my code I want my final output to be 25/06/2011.
Fiddle is # http://jsfiddle.net/tassadaque/rEe4v/
Date('string') will attempt to parse the string as m/d/yyyy. The string 24/06/2011 thus becomes Dec 6, 2012. Reason: 24 is treated as a month... 1 => January 2011, 13 => January 2012 hence 24 => December 2012. I hope you understand what I mean. So:
var dmy = "24/06/2011".split("/"); // "24/06/2011" should be pulled from $("#DatePicker").val() instead
var joindate = new Date(
parseInt(dmy[2], 10),
parseInt(dmy[1], 10) - 1,
parseInt(dmy[0], 10)
);
alert(joindate); // Fri Jun 24 2011 00:00:00 GMT+0500 (West Asia Standard Time)
joindate.setDate(joindate.getDate() + 1); // substitute 1 with actual number of days to add
alert(joindate); // Sat Jun 25 2011 00:00:00 GMT+0500 (West Asia Standard Time)
alert(
("0" + joindate.getDate()).slice(-2) + "/" +
("0" + (joindate.getMonth() + 1)).slice(-2) + "/" +
joindate.getFullYear()
);
Demo here
I would like to encourage you to use DateJS library. It is really awesome!
function onChange(e) {
var date = Date.parse($("#DatePicker").val()); //You might want to tweak this to as per your needs.
var new_date = date.add(n).days();
$('.new').val(new_date.toString('M/d/yyyy'); //You might want to tweak this as per your needs as well.
}
Assuming numberOfDaysToAdd is a number:
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
The first alert is the value of the field. the second is the generated date from a non-US formatted date.
Here is a working example (seems that this kind of markup is necessary to get noticed)
If you want to keep your code, then you need to change
var joindate = new Date(datepicker);
to
var parms = datepicker.split("/");
then use
var joindate = new Date(parms[1]+"/"+parms[0]+"/"+parms[2]);
OR the identically working
var joindate = new Date(parms[2],parms[1]-1,parms[0]);
As pointed out in a few other answers too, use the .getDate()
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
Lastly you want to add a 0 if the month is < 10
if (mm<10) mm="0"+mm;
If you are using the datepicker from jQuery UI, then you can do
$('.new').val($("#DatePicker").datepicker( "setDate" , +1 ).val());
instead of your function
http://jqueryui.com/demos/datepicker/#method-setDate
Sets the current date for the
datepicker. The new date may be a Date
object or a string in the current date
format (e.g. '01/26/2009'), a number
of days from today (e.g. +7) or a
string of values and periods ('y' for
years, 'm' for months, 'w' for weeks,
'd' for days, e.g. '+1m +7d'), or null
to clear the selected date.
Try
function onChange(e) {
var datepicker = $("#DatePicker").val();
alert(datepicker);
var parts = datepicker.split(/[^\d]/);
var joindate = new Date();
joindate.setFullYear(parts[2], parts[1]-1, parts[0]);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}
I suppose the problem is JavaScript expects format MM/DD/YYYY not DD/MM/YYYY when passed into Date constructor.
To answer your real problem, I think your issue is that you're trying to parse the text-value of the DatePicker, when that's not in the right format for your locale.
Instead of .val(), use:
var joindate = $('#DatePicker').datepicker("getDate");
to get the underyling Date() object representing the selected date directly from jQuery.
This guarantees that the date object is correct regardless of the date format specified in the DatePicker or the current locale.
Then use:
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
to move it on.
Is it a typo round joindate.setDate(joindate + numberOfDaysToAdd)?
I tried this code, it seems ok to me
var joindate = new Date(2010, 5, 24);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
alert(joinFormattedDate);
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + days);
return this;
};
and in your javascript code you could call
var currentDate = new Date();
// to add 8 days to current date
currentDate.addDays(8);
function onChange(e) {
var datepicker = $("#DatePicker").val().split("/");
var joindate = new Date();
var numberOfDaysToAdd = 1;
joindate.setFullYear(parseInt(datepicker[2]), parseInt(datepicker[1])-1, parseInt(datepicker[0])+numberOfDaysToAdd);
$('.new').val(joindate);
}
http://jsfiddle.net/roberkules/k4GM5/
try this.
Date.prototype.addDay = function(numberOfDaysToAdd){
this.setTime(this.getTime() + (numberOfDaysToAdd * 86400000));
};
function onChange(e) {
var date = new Date(Date.parse($("#DatePicker").val()));
date.addDay(1);
var dd = date.getDate();
var mm = date.getMonth() + 1;
var y = date.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}

Categories