Date format conversion in JavaScript - 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

Related

Display date in English and Japanese using moment.js or using JQuery/Javascript

I am using moment.js for formatting dates. I want to display date in 'en-JP' culture, but moment.js does not support 'en-JP' language.
Jquery/Javascript code would also be fine.
I want to display date like:
2018年 Aug月 15日 Wednesday
It seems "年", "月", "日" are Japanese for "year", "month", "day" so don't change with the date. So you don't need a library if there's reasonable support for the Intl object via toLocaleString, e.g.
var d = new Date();
var lang = 'en',
year = d.toLocaleString(lang, {year:'numeric'}),
month = d.toLocaleString(lang, {month:'short'}),
day = d.toLocaleString(lang, {day:'numeric'}),
dayName = d.toLocaleString(lang, {weekday:'long'});
console.log(
`${year}年 ${month}月 ${day}日 ${dayName}`
);
There is no such format (2018年 Aug月 15日 Wednesday) your are asking in Japanese culture.
But if you really need this format only you can get it like below using momentjs:
//2018年 Aug月 15日 Wednesday
var moment = moment();
console.log(moment.year() + "年 " + moment.format("MMM") + "月 " + moment.date() + "日 " + moment.format("dddd"));
console.log(moment.format('YYYY年 MMM月 D日 dddd'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

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.

Convert string as 'mm/dd/yyyy' to 'day of week, month name, year' in javascript

I am getting Facebook users' friends birthday back from Facebook in the following format:
10/07/1967 or just the day and month as 10/07
I want to display it as "October, 07, 1967" or "October, 07"
Is there a way to convert this string into a date and format it in Javascript?
var MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var myDate, myFormatDate;
var date_str ='10/07/1967';
var t = date_str.split("/");
if(t[2]) {
myDate = new Date(t[2], t[0] - 1, t[1]);
myFormatDate = MONTHS[myDate.getMonth()] + "," + myDate.getDate() + "," + myDate.getFullYear();
} else {
myDate = new Date(new Date().getFullYear(), t[0] - 1, t[1]);
myFormatDate = MONTHS[myDate.getMonth()] + "," + mydate.getDate();
}
= RESULT:
= myDate -- the Date Object
= myFormatDate -- formated date string "October, 07, 1967"
Check out the awesome DateJS library. You'll be able to do what you want, and more ...
[No, i'm not involved in any way with DateJs, just a very satisfied user :-)]
To do it fast, without bells and whistles, you can first split your date
myDateParts = myDate.split("/");
Then build the new date from the parts:
myNewDate = new Date(myDateParts[2], myDateParts[1], myDateParts[0]);
Using moment.js you can convert a date with:
moment('10/07/1967', "MM/DD/YYYY").format("MMMM, DD, YY")
where the first part get a date from a string given a format ("MM/DD/YYYY"), then you just format the date as you wish giving another format ("MMMM, DD, YY")
If you don't want to use a framework, you could just pass in the string to the date constructor:
var birthday = new Date('10/07/1967');
The constructor will also accept strings without year, like '10/07'.
Then you can access each of the properties as you wish:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

Google Feed API date to HTML5 datetime

The Google Feed API outputs the published date in the format: "13 Apr 2007 12:40:07 -0700".
I wish to change that to the valid HTML5 <time datetime="YYYY-MM-DDThh:mm:ssTZD"> using JS/jQuery.
Is there an easy way? Or a library?
Check out JavaScript Date Format. (Download here.) Then it's as easy as:
var input = "13 Apr 2007 12:40:07 -0700";
var date = Date.parse(input);
var output = dateFormat(date, 'yyyy-mm-dd"T"hh:MM:ssoD');
// output == 2007-04-13T12:40:07-0700D
Demo here: http://jsfiddle.net/pkC3s/2/
I started a solution for you in pure javascript by extending the Date object. However, I have to run now.
http://jsfiddle.net/2sYut/
Date.prototype.getHtml5String = function(){
return this.getFullYear() + "-" + this.getMonth() + "-" + this.getDay() + "T" + this.getHours() + ":" + this.getMinutes() + ":" + this.getSeconds() + "TZ" + this.getTimezoneOffset();
};
var d = new Date( "13 Apr 2007 12:40:07 -0700" );
alert( d.getHtml5String() );
Perhaps you can finish it off (or I will sometime today).
Hope that helps...
In the end I used the formatDate() function found here. The newer JS Toolbox didn't seem to have preserved this function (or at least didn't make it obvious).
var entryDate = new Date(entry.publishedDate); // From Google Feed API
html5date = formatDate(entryDate,'yyyy-MM-ddThh:mm:ss')+entryDate.toString().slice(28,33);
The slicing is to get the timezone, which formatDate didn't seem to support.
Here is the minified function, for preservation:
/*
* Author: Matt Kruse <matt#mattkruse.com>
* http://www.mattkruse.com/
* formatDate (date_object, format)
* Returns a date in the output format specified.
* The format string uses the same abbreviations as in getDateFromFormat()
*/
var MONTH_NAMES="January,February,March,April,May,June,July,August,September,October,November,December,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(","),DAY_NAMES="Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sun,Mon,Tue,Wed,Thu,Fri,Sat".split(",");function LZ(b){return(0>b||9<b?"":"0")+b} function formatDate(b,f){var f=f+"",h="",g=0,e="",c="",e=b.getYear()+"",c=b.getMonth()+1,i=b.getDate(),j=b.getDay(),d=b.getHours(),k=b.getMinutes(),l=b.getSeconds(),a={};4>e.length&&(e=""+(e-0+1900));a.y=""+e;a.yyyy=e;a.yy=e.substring(2,4);a.M=c;a.MM=LZ(c);a.MMM=MONTH_NAMES[c-1];a.NNN=MONTH_NAMES[c+11];a.d=i;a.dd=LZ(i);a.E=DAY_NAMES[j+7];a.EE=DAY_NAMES[j];a.H=d;a.HH=LZ(d);a.h=0==d?12:12<d?d-12:d;a.hh=LZ(a.h);a.K=11<d?d-12:d;a.k=d+1;a.KK=LZ(a.K);a.kk=LZ(a.k);a.a=11<d?"PM":"AM";a.m=k;a.mm=LZ(k);a.s= l;for(a.ss=LZ(l);g<f.length;){e=f.charAt(g);for(c="";f.charAt(g)==e&&g<f.length;)c+=f.charAt(g++);h=null!=a[c]?h+a[c]:h+c}return h};

Categories