I have a function which works well, for converting dates from a webservice returned in json format. The webservices gives dates in the following type of format:
Data example: The dates look like this in the json data
\/Date(1373875200000)\/
Current function: This is the current function I have
function HumanDate(date) {
var jsondateString = date.substr(6);
var current = new Date(parseInt(jsondateString));
var month = current.getMonth() + 1;
var day = current.getDate();
var year = current.getFullYear();
var hour = current.getHours();
var minute = current.getMinutes();
var datetime = day + "/" + month + "/" + year + " " + hour + ":" + minute
return datetime;
}
Usage: This is how I use the function above
success: function(data) {
if (data.d[0]) {
$.each(data.d, function(index, data) {
$("body").append(HumanDate(data.from) + '<br />');
});
} else {
Current output: This is the output I currently get, notice the missing 0's
2/7/2013 9:0
15/7/2013 9:30
15/10/2013 10:0
15/11/2013 10:30
Expected output: This is the output I would like, notice the extra 0's
02/07/2013 09:00
15/07/2013 09:30
15/10/2013 10:00
15/11/2013 10:30
Question:
How do I get the date and time formatted as the Expected output examples?
If you don't use a library, then you have to do some work, that is you have to put the "0" yourself.
Instead of simply concatenating day, you need to concatenate
(day<10 ? '0'+day : day)
and the same for the other fields.
But note that there are good javascript libraries filling this kind of gap. I personally used datejs for date manipulations.
I'd suggest using a library for this kind of thing -- something like Moment.js would do the job perfectly (and give you a load more functionality like date addition/subtraction into the bargain).
With moment.js, your code could look like this:
function HumanDate(date) {
return moment(date).format('MM/DD/YYYY HH:mm');
}
usage example:
alert(HumanDate("\/Date(1373875200000)\/"));
//alerts "07/15/2013 09:00"
Hope that helps.
You could also try moment.js. A 6.5kb library for formatting dates
var m = moment( new Date() );
m.format( "DD/MM/YYYY HH:mm");
Related
Am formatting the Date Format in JavaScript with the below code
function changeDateFormat(date) {
var fromJSON = new Date(parseInt(date.replace(/(^.*\()|([+-].*$)/g, '')));
return fromJSON.getMonth() + 1 + "/" + fromJSON.getDate() + "/" + fromJSON.getFullYear() + " " + fromJSON.getHours() + ":" + fromJSON.getMinutes();
}
i have 2 scenarios where i call the function with 2 diferent parameters
if date = "/Date(1374145967638)/" am getting the correct o/p
if date = "7/18/2013 4:28:52 PM" am getting Jan 01 1970
Is there a way i can write a common function in javascript/Jquery to handle both the dates ?
Am looking for an option without any JQUERY Plugins.
Thanks
I think you can first create a javascript Date object from date string then format it in what ever way you want.
ex:
var date = new Date("7/18/2013 4:28:52 PM");
then you can use different date class methods and format the string manually.
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 am able to get the output format that I need, but not the correct time. I need it in GMT (which is +4 hours)
var dt = new Date();
var dt2 = dt.toString('yyyyMMddhhmmss');
Any ideas? The output looks like:
20120403031408
I am able to get the GMT in standard string format by doing:
dt.toUTCString();
but im unable to convert it back to the yyyyMMddhhmmss string
EDIT: I am using the date.js library
date.js's toString(format) doesn't have an option to specify "UTC" when formatting dates. The method itself (at the bottom of the file) never references any of Date's getUTC... methods, which would be necessary to support such an option.
You may consider using a different library, such as Steven Levithan's dateFormat. With it, you can either prefix the format with UTC:, or pass true after the format:
var utcFormatted = dateFormat(new Date(), 'UTC:yyyyMMddhhmmss');
var utcFormatted = dateFormat(new Date(), 'yyyyMMddhhmmss', true);
// also
var utcFormatted = new Date().format('yyyyMMddhhmmss', true);
You can also write your own function, as Dominic demonstrated.
The key is to use the getUTC functions :
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
/* use a function for the exact format desired... */
function ISODateString(d){
function pad(n) { return n < 10 ? '0'+n : n }
return d.getUTCFullYear() + '-'
+ pad(d.getUTCMonth() +1) + '-'
+ pad(d.getUTCDate()) + 'T'
+ pad(d.getUTCHours()) + ':'
+ pad(d.getUTCMinutes()) + ':'
+ pad(d.getUTCSeconds()) + 'Z'
}
var d = new Date();
console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z
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
I wondering what is the best way to convert a timestamp of this format -
2012-02-18 14:28:32
to a date presentation of this format -
Saturday Feb 2012 14:28:32
Many thanks :)
Javascript date functions are pretty bad... You have the option to convert to UTC http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_toutcstring
But if it was me, i would look into Datejs: http://www.datejs.com/ best javascript date api for me
Please take a look at the getting started with Datejs: http://www.datejs.com/2007/11/27/getting-started-with-datejs/
You must first define an array of the English words (Sunday, Monday, Feb, Mar, etc.):
var daysOfWeek = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
monthsOfYear = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
To be able insert the extra 0 at the beginning of the minutes and seconds, define a padding function for the String prototype:
String.prototype.padLeft = function(padString,length){
var toReturn = String(this);
while(toReturn.length < length){
toReturn = padString + toReturn;
}
return toReturn;
}
Format the date and time like this:
var time = new Date(), formattedDate, formattedTime, wholeThing;
formattedDate = daysOfWeek[time.getDay()] + ", " + monthsOfYear[time.getMonth()] + " " + time.getDate() + ", " + time.getFullYear();
formattedTime = time.getHours() + ":" + time.getMinutes().padLeft("0",2) + time.getSeconds().padLeft("0",2);
You can get the whole thing by concatenating formattedDate and formattedTime, as in:
wholeThing = formattedDate + " " + formattedTime;
Consider using datejs which is rocks!
var mydate = Date.parse('2012-02-18 14:28:32');
var result = mydate.toString('dddd MMM yyyy h:mm:ss');
console.log(result);
I'd suggest using an external js library to do that. To my understanding, Moment.js is the best date-time conversion library out there.
In this case, it does the job in one line. Just add the moment.js in you project and then do
var timestamp = '2012-02-18 14:28:32';
var formattedTime = moment(timestamp).format('dddd MMM YYYY HH:mm:ss'); // Saturday Feb 2012 14:28:32
JavaScripts Date object is lacking methods for formatting. I would consider using an external library like this one. Seems it has what you're looking for.
try this blog it has enough dateformats:
http://blog.stevenlevithan.com/archives/date-time-format