Date format of value from md-datepicker - javascript

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.

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

How to extract values from HTML <input type="date"> using jQuery

Using an HTML input type="date" and a submit button. I would like to populate the variables day, month, and year with the appropriate values from the date input.
<input type="date" id="date-input" required />
<button id="submit">Submit</button>
and the jQuery:
var day, month, year;
$('#submit').on('click', function(){
day = $('#date-input').getDate();
month = $('#date-input').getMonth() + 1;
year = $('#date-input').getFullYear();
alert(day, month, year);
});
Here's a code sample:
https://jsfiddle.net/dkxy46ha/
the console error is telling me that .getDate() is not a function.
I have seen similar questions but the solutions have not worked for me. How can I extract the day, month and year from the input type="date"? Thanks
Firstly you need to create a Date object from input element value. And then you will be able to get day, month and year from this object.
$('#submit').on('click', function(){
var date = new Date($('#date-input').val());
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
alert([day, month, year].join('/'));
});
Working example: https://jsfiddle.net/8poLtqvp/
Date value returned by input type="date" is format yyyy-mm-dd . Could use .split() with argument "-" to retrieve array containing [yyyy, mm, dd]
Note, alert() expects string as parameter ; does not print values same as console.log() with comma , operator
var day, month, year;
$('#submit').on('click', function() {
var date = $('#date-input').val().split("-");
console.log(date, $('#date-input').val())
day = date[2];
month = date[1];
year = date[0];
alert(day + month + year);
});
jsfiddle https://jsfiddle.net/dkxy46ha/2/
date = new Date($('#date-input').val())
date.getDate()
...
<input type="date" id="date-input"/>
<input type="submit" id="submit" value="submit"/>
<script>
$('#submit').on('click', function(){
var date = new Date($('#date-input').val());
var day = $('#date-input').getDate();
var month = $('#date-input').getMonth() + 1;
var year = $('#date-input').getFullYear();
alert(day+"/"+ month+"/"+year);
});
</script>
Date class will convert input data into date type. Then getMonth() gives us value from 0-11 so we can either consider January
as 0 or we can add 1 to received value that's what I did here.
Here I just used Jquery to fetch date, months and year respectively and if you want to post the data you can convert that values into string.
The Advantage of JQuery ? A few lines of code do a lot !!
alert only takes a string as its parameter.
So simply, we just have to pass our Date object as a string using th String built-in-Function.
Just replace the button tag with this...
<button onclick="alert(String( $("#date-input").val() ))">Submit</button>
You can do further manipulations on the string you'll be alerted as yyyy-mm-dd

parse string date to date object in javascript

I have a date in this format: '04-Aug-15'.
I want to be able to get a Date object in JS, I'm trying this:
var date = new Date(Date.parse('04-Aug-15', "MM/dd/yyyy"));
But I'm getting invalid date error message.
Any idea how can I fix this?
Just pass new Date the date string, and it'll turn it into a date.
var stringDate='04-Aug-15';
var date=new Date(stringDate);
console.log(date);
Try this to parse your date.
var date = new Date(Date.parse("04-Dec-15"));
You can then print your date by the following function.
window.alert( (date.getMonth() + 1) +
'/' + date.getDate() + '/' + date.getFullYear());

Angularjs Input date format short date

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

How to format a date pulled from a form field with javascript

I have a date picker that generates a date like 6/30/2012 in a form field.
I need to convert this date to 2012-06-30 for mysql. I can get it close with the following.
var datePart=document.getElementById('formdate').value.split(/[^0-9]+/);
and then use to generate the date.
datePart2[2] + "-" + datePart2[1] + "-" + datePart2[0]
The problem is it gived me the date 2012-6-30 instead of 2012-06-30.
Is there an easier way to do this? Or a way to use my current method and ad a zero to the front of a digit if it is a single digit?
The Open Source date.js ( http://www.datejs.com/ )provides a really extensive framework for JavaScript dates, IMHO superior to the jQuery plug-in. It may be more than you need for this requirement, but I think it is a welcome addition to any JavaScript programmers's arsenal.
To format your example:
var mySqlDate = Date.parse('6/30/2012').toString('yyyy-MM-dd');
Are you using jQuery? if so you could use the Date Format plugin, makes date manipulation easy
http://archive.plugins.jquery.com/project/jquery-dateFormat
try this, hope this help:
Format date in jquery- from Sat Mar 03 2012 14:16:05 GMT+0530 to 03/03/2012
important you need to put a check condition like this one and if its less then 10 append 0 [code] date < 10 ? "0"+date : date; cheers!
something on the line of this:
function dateFormatFoo(){
var d = new Date();
date = d.getDate();
date = date < 10 ? "0"+date : date;
mon = d.getMonth()+1;
mon = mon < 10 ? "0"+mon : mon;
year = d.getFullYear()
return (date+"/"+mon+"/"+year);
}
Based on your example, a simple function is:
var formatUStoISOdate = (function() {
function aZ(n) {
return (n<10? '0' : '') + n;
}
var re = /[^0-9]/;
return function(d) {
var d = d.split(re);
return d[2] + '-' + aZ(d[0]) + '-' + aZ(d[1]);
// or
// return [d[2], aZ(d[0]), aZ(d[1])].join('-');
}
}());
alert(formatUStoISOdate('3/31/2011')); // 2011-03-31

Categories