I'm trying to parse a date to mm/dd/yyyy format.
My function:
function formatDate(value) {
// value = '2016-07-05T00:00:00-04:00'
var dt = new Date();
dt = Date.parse(value); // dt = 1467691200000
return dt.getMonth() + 1 + "/" + dt.getDate() + "/" + dt.getFullYear();
}
I'm getting this error:
dt.getMonth is not a function
It seems that dt isn't a valid date so I can't access getMonth() method. Just not sure what I need in order to get this to work.
Date.parse() doesn't returns an object type Date, you can check it: console.log(typeof dt);.
So, you can do it using toLocaleDateString method.
Here's is the snippet working:
function formatDate(value) {
var dt = new Date(value);
dt.setMonth(dt.getMonth() + 1);
console.log(dt.toLocaleDateString());
}
var dates = ['2016-05-04T00:00:00-04:00', '2013-07-05T00:00:00-02:00', '2015-04-06T00:00:00-01:00'];
for (var i = 0; i < dates.length; i++) {
formatDate(dates[i]);
}
Note: toLocaleDateString method uses your locale conventions, in other words, it can returns in another format for another user.
I hope it helps.
Try to pass value as a parameter when creating the Date, instead of separately calling the parse function.
function formatDate(value) {
var dt = new Date(value);
return dt.getMonth() + 1 + "/" + dt.getDate() + "/" + dt.getFullYear();
}
Related
To format the date, I tried prototyping a method.
Date.prototype.formatYYYYMMDDHHMMSS = function() {
return (this.getFullYear() + eval(this.getMonth() + 1)
+ this.getDate() + this.getHours() + this.getMinutes() + this.getSeconds());
};
var upload = Date.now();
var uploadDate = upload.formatYYYYMMDDHHMMSS();
But following error is shown:
upload.formatYYYYMMDDHHMMSS is not a function
That's because Date.now() returns number of milliseconds elapsed since 1 January 1970 00:00:00 UTC and not a Date object.
The correct way of using your approach would be:
var upload = new Date();
var uploadDate = upload.formatYYYYMMDDHHMMSS();
Use a date object var upload = new Date();
edit:
the ctor Date() default is now.
This might be a simple solution but I am stuck, basically I need convert an incoming yyyy-MM-dd to MM/dd/yyyy also, if incoming date is nil, then output should also be nil.
Incoming date could be of following format
2015-01-25 or nil
Output date shoud be
01/25/2015 or nil
I was trying one from the following link
Convert Date yyyy/mm/dd to MM dd yyyy but couldn't make it work.
Thanks for any help.
Forgot to mention, the incoming date which comes as nil is of the following format in an xml file
<Through_Date__c xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
So if I get the above format the output should be just be nil
The date toString function has some support for formatting. See this. And you also want to handle the undefined case which I took from here. So, for your case you can just do this:
function format(inputDate) {
var date = new Date(inputDate);
if (!isNaN(date.getTime())) {
// Months use 0 index.
return date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();
}
}
EDIT: Addressing the comment
If the padding is important you just need to add that in:
var d = date.getDate().toString();
(d[1]?d:"0"+d[0])
I've made an update to the fiddle
Try using RegEx:
var format = function(input) {
var pattern = /(\d{4})\-(\d{2})\-(\d{2})/;
if (!input || !input.match(pattern)) {
return null;
}
return input.replace(pattern, '$2/$3/$1');
};
console.log(format('2015-01-25'));
console.log(format('2000-12-01'));
console.log(format(''));
console.log(format(null));
Using String#split and Array#join, push & shift:
var format = function(input) {
var array = (input || '').toString().split(/\-/g);
array.push(array.shift());
return array.join('/') || null;
};
console.log(format('2015-01-25'));
console.log(format('2000-12-01'));
console.log(format(''));
console.log(format(null));
if you wanna go ghetto style and use easily understandable code, and you dont care about using a date object, try this!
function changeDateFormat(inputDate){ // expects Y-m-d
var splitDate = inputDate.split('-');
if(splitDate.count == 0){
return null;
}
var year = splitDate[0];
var month = splitDate[1];
var day = splitDate[2];
return month + '\\' + day + '\\' + year;
}
var inputDate = '2015-01-25';
var newDate = changeDateFormat(inputDate);
console.log(newDate); // 01/25/2015
you can deal your javascript dates in various formats.
For dd/MM/yyyy you can use
var date = new Date().toLocalDateString()
or
var date = new Date('2021-07-28').toLocalDateString()
output: '28/07/2021'
For MM/dd/yyyy
var date = new Date().toLocaleDateString("en-US", { year: "numeric", month: "2-digit", day: "2-digit" })
or
var date = new Date('2021-07-28').toLocaleDateString("en-US", { year: "numeric", month: "2-digit", day: "2-digit" })
output: '07/28/2021'
Alternatively you can handle custom date formats using following date functions
let date = new Date()
let dateString = [
date.getMonth() + 1,
date.getDate(),
date.getFullYear(),
].join('/')
}
output: 07/28/2021
If your date has not yet been parsed from a string, you can simply rearrange its components:
var s = '2015-01-25';
if (s) {
s = s.replace(/(\d{4})-(\d{1,2})-(\d{1,2})/, function(match,y,m,d) {
return m + '/' + d + '/' + y;
});
}
Thanks guys, I was able to do grab some ideas from all your posts and came up with this code which seems to working fine in my case
if((typeof inStr == 'undefined') || (inStr == null) ||
(inStr.length <= 0)) {
return '';
}
var year = inStr.substring(0, 4);
var month = inStr.substring(5, 7);
var day = inStr.substring(8, 10);
return month + '/' + day + '/' + year;
You can also try the method below using vanilla JS. I have converted the date to a string & parsed it to get the format you're looking for:
function tranformDate(strDate) {
let result = '';
if (date) {
let parts = date.split('-');
result = `${parts[1]}/${parts[2]}/${parts[0]}`;
}
return result;
}
let date = new Date().toISOString().split('T')[0];
console.log('raw date: ' + date);
console.log('formatted date: ' + tranformDate(date));
I am using jquery autocomplete onselect it is showing data in different text field. I am showing formatted date in #dob and #anniversery by using format_date() function
select: function(event, ui) {
$("#customerId").val(ui.item.id);
$("#customerName").val(ui.item.value);
var datefield = new Date(ui.item.dob);
$("#dob").val(format_date(datefield));
var datefield1 = new Date(ui.item.anni);
$("#anniversery").val(format_date(datefield1));
$("#address").val(ui.item.address);
$("#mobNo").val(ui.item.mobno);
},
});
function format_date(dt) {
alert(dt);
var dd = dt.getDate();
var mm = dt.getMonth() + 1; //January is 0!
var yyyy = dt.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
dt = mm + '/' + dd + '/' + yyyy;
return dt;
}
});
Above code is working properly if ui.item.dob and ui.item.anni is not null.
In case of null it is showing NaN/NaN/NaN
If date value is empty it should not show anything in textbox.
alert(dt) prints Invalide date.
How to resolve this.
You can check whether a Date instance is an invalid date by checking one of the properties for NaN:
function format_date(dt) {
if (isNaN(dt.getFullYear())) return "";
// ...
}
In your function, check that the Date object is okey using isNaN function. Also, there's an easier way of formating the date as you want, with out all the ifs:
function format_date(dt) {
if(isNaN(dt.getTime()) return "";
return dt.getFullYear + '/' + String('00' + (dt.getMonth() + 1)).slice(-2) + '-' + String('00' + dt.getDate()).slice(-2);
}
Also good to know is that initializing a Date object like var datefield = new Date(ui.item.dob); has a bit poor browser support (
A more safe way of doing it is to initialize the Date object without any proporties, var datefield = new Date(); and the using the Date set*() functions to set the time. A whole lot more code, but if you need it to work in old browsers...
Example
http://jsfiddle.net/HMb68/
var inDateTime = '2014-07-26 17:52:00',
inDateTimeSplit = inDateTime.split(' '),
inDateParts = inDateTimeSplit[0].split('-'),
inTimeParts = inDateTimeSplit[1].split(':'),
outDate = new Date;
outDate.setFullYear(parseInt(inDateParts[0], 10));
outDate.setMonth((parseInt(inDateParts[1], 10) - 1));
outDate.setDate(parseInt(inDateParts[2], 10));
outDate.setHours(parseInt(inTimeParts[0], 10));
outDate.setMinutes(parseInt(inTimeParts[1], 10));
outDate.setSeconds(parseInt(inTimeParts[2], 10));
outDate.setMilliseconds(0);
console.log(outDate);
I am getting DATETIME strings in the following format from the facebook API:
2013-12-15T19:00:00-0800
I want to format this so I can properly insert it into an SQL date column. Below is the jist of the approach I've been taking. I am able to insert it into the database using these formatting techniques but when I try an SQL mechanism such as ORDER BY DATE it's not working.
var newDate = new Date('2013-12-15T19:00:00-0800').getTime() / 1000
Another approach:
var test = new Date('2013-12-15T19:00:00-0800')
//var newDate = new Date(test.getFullYear(), test.getMonth(), test.getDate());
Edit:
Below is a function showing some additional attempts at formatting the date as per the suggestions below. The order by hasn't worked for any of these approaches and the the returned type from the select statement is still "string".
function fbStampToDbDate(fbTimeOffSet){
if(fbTimeOffSet.indexOf('T') > 0){
var date = new Date(fbTimeOffSet.substring(0, fbTimeOffSet.indexOf('T')));
var fbStamp = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
var stamp = fbTimeOffSet.split("T");
}else{
var date = new Date(fbTimeOffSet);
var fbStamp = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
var stamp = fbTimeOffSet.split("T");
}
//return fbStamp;
return stamp[0];
}
I get the response for the Date in this format while showing in the text box, how do i covert it to MM/DD/YYYY and Again re covert it to back to this format while sending
/Date(1306348200000)/
function dateToString(date) {
return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getYear();
}
function dateFromString(str) {
return new Date(str);
}
Note, that month begins from 0.
To convert the regExp-like string to a real Date Object you could use:
var dateNum = Number('/Date(1306348200000)/'.replace(/[^0-9]/g,''))
, dat = new Date(dateNum); //=>Date {Wed May 25 2011 20:30:00 GMT+0200}
To display formatted dates I use my own small library, which may be of use to you.
var s = '/Date(1306348200000)/';
// convert to javascript date
var date = new Date(parseInt(s.substr(6, 13))); // removes /Date( & )/
// format the date
function pad(n) { return n < 10 ? '0' + n : n; } // leading zeros
var ddmmyy = pad(date.getDate()) + '/' + pad(date.getMonth() + 1) + '/' + date.getFullYear().toString().substr(2);
// convert back
s = '/Date(' + date.getTime() + ')/';
here you can find everything regarding javascript dates http://www.w3schools.com/js/js_obj_date.asp