Common FormatDate function for different date formats - javascript

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.

Related

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

Leading 0 missing from data and time

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

Is there any way to format the date of a field in a query? [duplicate]

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.

Get GMT String from current 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

Date format conversion in JavaScript

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

Categories