Angularjs Input date format short date - javascript

We return json from our services and we have a parser that converts these json dates to dates we can use and display. But id like to display just the short date - we dont need to show the time.
<input type="text" class="form-control"
ng-model="DateOrdered"
datepicker-popup="shortDate"
show-weeks="false" />
id like to see - 11/11/2012 not 11/11/2012 3:00:00
I cant put a value on this input since im using ng-model. id like to not build some custom filter or directive - but i may have too - wondering if angularjs has something out of the box for this.
thanks in advance.

I wound up building a custom date directive. date-format
ngModelController.$formatters.unshift(function (valueFromModel) {
if (angular.isUndefined(valueFromModel) || valueFromModel == "" || valueFromModel == null) {
return valueFromModel;
}
var date = new Date(valueFromModel);
var _date = date.getDate();
var _month = date.getMonth() + 1;
var _year = date.getFullYear();
return _month + "/" + _date + "/" + _year;
});

Related

How do I pass the JSON date value from a textbox and convert it in Javascript?

I'm returning a date to a text box using JSON, this means my date is returned as a string like this:
/Date(1335205592410)
Can anyone tell me how I can access this date from my textbox and convert it to a useable date format i.e. DD/MM/YYYY There are many guides online but most of them suggest using substr(6), with my value being in a textbox I'm not sure how I'd use that approach. I access my textbox like so:
function dateChange() {
var date_box = document.getElementById('date').value;
...
... Code to populate textbox ...
...
}
The textbox is a generic html textbox, when the above function runs it populates it with the JSON date string.
<input id="date" name="date" />
I need help getting the date value from the textbox and then converting it to a useable date. Can anyone help me out?
Many thanks
Does this work ok?
var date = new Date(1335205592410);
var day = "0" + date.getDate();
var month = "0" + date.getMonth();
var year = date.getFullYear();
var formattedDate = day.substr(-2) + '/' + month.substr(-2) + '/' + year;
alert(formattedDate);
Microsoft .Net handles this date format, you can overcome by gettings the miliseconds inside de Date string.
implementation
var convertMSDate = (function() {
var pattern = /Date/,
replacer = /\D+/g;
return function(date) {
if (typeof date === "string" && pattern.test(date)) {
date = +date.replace(replacer, "");
date = new Date(date);
if (!date.valueOf()) {
throw new Error("Invalid Date: " + date);
}
}
return date;
}
}());
usage
var date = '/Date(1335205592410)';
console.log(convertMSDate(date));
// use ISO 8601 format
date = convertMSDate(date);
console.log(date.toISOString());
// get date parts
var year = date.getFullYear(),
month = date.getMonth() + 1,
day = date.getDate();
console.log([day, month, year].join('/'));

Date format of value from md-datepicker

How to format model variable of md-datepicker in particular format. I tried config of $mdDateLocaleProvider, But it just formatted the display value of date-picker, not the model value. Please look at this codepen or below code:
HTML:
<div ng-app="MyApp" ng-controller="AppCtrl">
<md-content>
<md-datepicker ng-model="myDate" md-placeholder="Enter date"></md-datepicker>
</md-content>
<p>Date not formatted:</p>
{{myDate}}
</div>
JS:
angular.module('MyApp')
.controller('AppCtrl', function($scope) {
$scope.myDate = new Date();
})
.config(function($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return moment(date).format('YYYY-MM-DD');
};
});
You should use the angular 'date' filter
{{myDate | date:'yyyy-MM-dd'}}
For more formatting and other info see: https://docs.angularjs.org/api/ng/filter/date
var dateFormat = function(date) {
var date = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
var formattedDate = (date < 10 ? ('0' + date) : date) + '/' + (month < 10 ? ('0' + month) : month) + '/' + year;
}
Or
return date.getDate() + "/" +date.getMonth()+1 + "/" + date.getFullYear();
Will give your 01/08/2016. (You need to +1 getMonth() because January is 0). Is this what you are looking for?
Edit: function
The model object is always a javascript date object, you can only change the representation when you render it (for example with moment as you do, or the already mentioned angular date filter).
Maybe you should read up on date formats in javascript and in JSON: The “right” JSON date format
You can however transform the date object before you send it to your server/backend.
If you use REST with $resource or $http you can use something like angular-http-transform-date or do it on your own by adding a request transformer to the $httpProvider.
There is a blog post which shows how to do it for responses, but the same mechanism applies for requests.

Incrementing Date Field using Javascript in Adobe Acrobat

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

Change date format who is stored in text field

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...

I want to pass back a variable from a promt box to the date string

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

Categories