I have a common date field having a displayDD-MM-YYYY but the real value stored in database is YYYY-MM-DD. The problem is this value is also transmitted to a remote server inside a simple text field (having readonly properties) and I would like interact on this field for change his display in DD-MM-YYYY.
I don't want touch something in database structure for change the way on how the date is stored. I precise I don't have access to html of this remote server but I'm allowed to modify some field by putting code in JS file.
I looked here and in some forum but I don't find a solution and due to my poor javascript knowledge I'm stuck. Thank.
Use inbuilt javascript functions to build the format you want. PArse the string in to a date object and use the following functions to create your desired format
getDate() -> to get date
getMonth() -> to get month
getFullYear() -> to get year
Example
//var birth_date = document.getElementById('birth_date');
//use birth_date instead of hard coded date
//var day = new Date(Date.parse(birth_date));
var day = new Date(Date.parse("2013-09-02"));
alert(day.getDate() + "-" + day.getMonth() + "-" + day.getFullYear());
//set value
document.getElementById('birth_date').value = day.getDate() + "-" + day.getMonth() + "-" + day.getFullYear();
JSFIDDLE
Say you have a string var s = '1989-05-06';. You can get the year, month and day separately like so:
var my_date = s.split('-');
var year = my_date[0];
var month = my_date[1];
var day = my_date[2];
Then, you can display the string below (or organize the day, month and year in any format you would like):
var display_str = '' + day + '-' + month + '-' + year;
You can catch the form submit event and change the value before it is sent:
Let's say you have a form #myForm:
var form = document.getElementById('myForm');
To catch submission:
try {
form.addEventListener("submit", changeValue, false);
} catch(e) {
form.attachEvent("onsubmit", changeValue); //Internet Explorer 8-
}
Now you can change the desired value inplace.
function changeValue(){
var field = document.getElementById('idOfField');
field.value = field.value.split('-').reverse().join('-');
}
well, we can do that using simple javascript function.
we just need to pass server date(YYYY-MM-DD) and it wll return expected date (DD-MM-YYYY) format.
function convertDate(serverDate) {
var dateCollection = serverDate.match(/\d+/g),
year = dateCollection[0],
month = dateCollection[1],
day = dateCollection[2];
return day + '-' + month + '-' + year;
}
Example:-
convertDate('2013-09-02'); // (YYYY-MM-DD) format
output:-
'02-09-2013' //(DD-MM-YYYY) format
Hope this will help you...
Related
I am trying to convert a date string into a date object within javascript. My date has the following format:
"13.02.2015 12:55"
My current approach was:
var d = new Date("13.02.2015 12:55");
But this didnt work and always returns invalid date. If I enter a date as "12.02.2015 12:55" it works in chrome but not in firefox.
I guess this is because he thinks the first part is the month, but in germany this is not the case.
How can I get this to work?
use moment.js:
var date = moment("13.02.2015 12:55", "DD.MM.YYYY HH.mm").toDate();
Update 2022-05-28:
Meanwhile the project status of moment.js has changed. Therefore I strongly suggest to read https://momentjs.com/docs/#/-project-status/ and observe the recommendations.
try the ISO 8601 format,
or better yet, read this http://www.ecma-international.org/ecma-262/5.1/#sec-15.9
Edit: if you have no other choice than to get it in that format though, i guess you'll need something like this:
function DDMMYYYY_HHMMtoYYYYMMDD_HHMM($DDMMYYYY_HHMM) {
var $ret = '';
var $foo = $DDMMYYYY_HHMM.split('.');
var $DD = $foo[0];
var $MM = $foo[1];
var $YYYY = $foo[2].split(' ') [0].trim();
var $HH = $foo[2].split(' ') [1].split(':') [0].trim();
var $MMM = $foo[2].split(' ') [1].split(':') [1].trim();
return $YYYY + '-' + $MM + '-' + $DD + ' ' + $HH + ':' + $MMM;
}
var d=new Date(DDMMYYYY_HHMMtoYYYYMMDD_HHMM('13.02.2015 12:55'));
I'm trying to create a form that automatically increments date fields by a month depending on what the user puts into the first field. I've dug through some javascript and am thinking that the issue may lie in the way Adobe date fields are formatted and what Date() in javascript accepts as input. So for this example I want what is entered in date field to increment by one month and be put into date1 field. Below is my effort.
var two = this.getField("date1");
var date = new Date(this.getField("date"));
two.value = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
This is entered in date's action field.
I was able to resolve the issue by doing this and incrementing the getMonth() call and setting it to the variable before displaying the date in a formatted way.
var nDate = new Date(inputBox.value);
nDate.setMonth( nDate.getMonth( ) + 1 );
inputBox1.value = (nDate.getMonth() + 1) + "/" + (nDate.getDate()) + "/" + (nDate.getFullYear());
I've got a problem with date object in IE8, and some older browsers. On website I have input hidden, where I keep date, and after change new date should be in that field.
On my machine everything is fine, but on some others I get NaN-NaN-NaN, that's my code:
var date = new Date($('#curDate').val());
//date.setDate(date.getDate() - 7);
var dateMsg = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
alert(dateMsg);
When I run this file (php), in hidden input I've got Monday's date from the current week 2013-03-25.
This alert return me NaN-N.. on Win XP IE8, and on very old mac, I recon it's problem with object. How to take date value and convert it to object in javascript?
Never use new Date(some_string) - it's unreliable because it depends on the user's locale.
Break the string into its yy/mm/dd components yourself and then call new Date(y, m - 1, d)
Problem with your hyphens..
Convert your hyphens('-') with slashes('/')
var dateStr=$('#curDate').val();
var a=dateStr.split(" ");
var d=a[0].split("-");
var t=a[1].split(":");
var date = new Date(d[0],(d[1]-1),d[2],t[0],t[1],t[2]);
or
var date=new Date(convertToSlash($('#curDate').val()));
function convertToSlash(string){
var response = string.replace(/-/g,"/");
return response;
}
You can also use new Date(some_string) format. It's reliable. However, the datestring must be in ISO format that is yyyy/mm/dd.
This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 9 years ago.
I am getting a query with a field in an undesired date format (Thu Feb 21 00:00:00 EST 2013)
Is there any way to modify this to mm-dd-yyy?
I am using javascript, I found a php way to do it, but sadly it has to be in javascript, so the instruction has to be pretty much the same way it would be in TOAD.
I tried the CONVERT() method and it didn't work. I am not sure I am using it right though
The Convert() function will work, but you need to use the correct format code from here:
SQL Convert() Function.
SELECT Convert(char(10), #date, 110)
Date.js is pretty handy for date formatting.
you probably could try converting to a unix timestamp, then formatting. I havent tested this, and it will probably throw an error, but you get the idea.
var input = your date;
input = input.split(" - ").map(function (date){
return Date.parse(date+"-0500")/1000;
}).join(" - ");
var year = input.getYear();
var month = input.getMonth();
var day = input.getDay();
var hours = input.getHours();
var minutes = input.getMinutes();
var seconds = input.getSeconds();
var formatted = month + " " + day + ", " + year + " at " hours + ':' + minutes + ':' + seconds;
There are basic Date object functions in JS that you can use.
First, create the date variable:
var date = new Date('your date value');
Then you can access the individual date pieces:
var month = date.getMonth() + 1; //gets the month . . . it's 0-based, so add 1
var day = date.getDate(); //gets the day of the month
var year = date.getFullYear(); //gets the 4-digit year
Once you have those values, you can concatenate them in any format that you'd like. For a basic mm-dd-yyyy, use:
var formattedDate = month + "-" + day + "-" + year;
There time and timezone values are also available.
That's a badly mixed up format. There are two basic ways to modify it, one is to just re–order the bits you have, the other is to convert it to a date object and use that to create the new string. Either way, you haven't said what to do with the timezone offset.
Using abbreviations or names for timezones is ambiguous, there is no standard for them and some are duplicted (EST is used for three different timezones). In any case, a simple re–ordering can be:
function formatDate(s) {
var months = {jan:'01', feb:'02', mar:'03', apr:'04',
may:'05', jun:'06', jul:'07', aug:'08',
sep:'09', oct:'10', nov:'11', dec:'12'};
var s = s.split(' ');
var d = (s[2] < 10? '0' : '') + s[2];
return months[s[1].toLowerCase()] + '-' + d + '-' + s[5];
}
alert(formatDate('Thu Feb 21 00:00:00 EST 2013')); // 02-21-2013
The output format (mm-dd-yyyy) is ambiguous, consider using something like 21-Feb-2013 or a standard format like ISO8601 (2013-02-21).
If you need to consider the timezone, it will be easier to create a date object, add the offset, then get back the new date. However, you will also need to work out how to convert the string timezone to a number (preferably minutes, but hours is OK) that can be used with the date.
I want to pass back a variable from a promt box to the date string. So if a person adds 5 days the date will bump up 5 days. I am new to javascript and this is my first test script any resources you could list in your answer I will read up on.
<html>
<head>
<script type="text/javascript">
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var dateString = "Today's Date " + month + "/" + day + "/" + year;
function loadDate(){
document.getElementById('dateSpan').innerHTML = dateString;
}
</script>
</head>
<body onload='loadDate()'>
<form name=myform>
<span id='dateSpan'></span><input type=button value="add days" onclick="var name=prompt('How many days do you want to add?','5 or 6')"/>
</form>
</body>
Something like the following should help. Note that it doesn't do any validation or checking (is the date string correct in the element? did the user enter a number?) so you'll need to add all that and deal with errors.
function updateDate(el) {
// get the text of the element
var text = el.innerHTML;
// Convert to a date object
var b = text.split('-');
var date = new Date(b[0], b[1] - 1, b[2]);
// Ask for days to add
var toAdd = prompt('How many days to add?');
// Adjust date
date.setDate(date.getDate() + Number(toAdd));
// Write date to page
el.innerHTML = date.getFullYear() + '-' +
addZ(date.getMonth() + 1) + '-' +
addZ(date.getDate());
// Helper just for this function
function addZ(n) {
return (n < 10? '0' : '') + n;
}
}
And some related HTML:
<span id="dateSpan" onclick="updateDate(this)">2012-05-22</span>
Note also that innerHTML gets all the HTML content too, but for something like this it shoudl be fine. If you need just the text, then use either textContent or innerText based on a feature test for which is supported.
Edit
Added a snipped of HTML to make it work. Note that the date is an ISO8601 short form: year-month-day.
I'd go with using the date.js lib.
This makes dates a lot easier to work with and it's well documented too.
http://www.datejs.com/
Then once you have the number of days to add you can easily bump the date up.
//Assuming Xdays is a var with your number of days.
var today = Date.today();
var past = Date.today().add(-Xdays).days();
var future = Date.today().add(Xdays).days();
//format to a string
Date.today().toString("d-MMM-yyyy"); // 19-Nov-2007