datetime formatting in javascript - javascript

When I generate a date with the following code
var date = new Date();
I get a date-time of the following form
Sat May 11 2013 21:54:23 GMT-0700 (PDT)
Can anyone tell me how to generate a date of the form below without using regex/string functions.
Sat May 11 2013 21:54:23

Try giving this a shot: http://blog.stevenlevithan.com/archives/date-time-format
It has a collection of Date format options that I believe would give you what you desire.
Ignoring the above Javascript library and doing it native:
var date = new Date();
date = date.toDateString() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
Does this work ok for you?

Javascript does not come with a date formatting library beyond the one specific format you see. You can either build your own by piecing together the exact pieces you want and adding the strings together or you can get a third party date formatting library.
If you want a 3rd party library, the Datejs library is pretty thorough. In that library, it would be:
Date.today().toString("ddd MMM d yyyy H:mm:ss");
You could, of course obtain all the component values from the built-in date object and then build your own string too.
Without adding a library, you'd have to write your own way to make that specific format:
function formatDate(date) {
function makeTwoDigits(val) {
var prefix = val <= 9 ? "0" : "";
return prefix + val;
}
var dayOfWeek = date.getDay(); // 0-6, 0=Sunday
var month = date.getMonth(); // 0-11
var day = date.getDate(); // 1-31
var year = date.getFullYear(); // 2013
var hours = makeTwoDigits(date.getHours()); // 0-23
var mins = makeTwoDigits(date.getMinutes()); // 0-59
var secs = makeTwoDigits(date.getSeconds()); // 0-59
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
return days[dayOfWeek] + " " + months[month] + " " + day + " " + year + " " +
hours + ":" + mins + ":" + secs;
}
Working demo: http://jsfiddle.net/jfriend00/zu7Uz/

Related

Javascript - How to get date in needed format? [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 6 years ago.
Want to get Date output in 2 different formats. Here is what i have at the moment.
<p id="demo"></p>
<script>
var d = new Date(day, month);
document.getElementById("demo").innerHTML = d.toString();
</script>
Does not work for me.
With this code i want to get this output: 21 Jun
Also would like to know how to get date in this format:
Jun 21, 2016 12:00 AM
var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var h = d.getHours();
var ap = "AM";
if (h > 12) {
h-=12;
ap = "PM";
}
var dateString = months[d.getMonth()] + " " + d.getDate() + ", " + d.getFullYear() + " " + h + ":" + d.getMinutes() + " " + ap;
var d = new Date();
var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var h = d.getHours();
var ap = "AM";
if (h > 12) {
h-=12;
ap = "PM";
}
var dateString = months[d.getMonth()] + " " + d.getDate() + ", " + d.getFullYear() + " " + h + ":" + d.getMinutes() + " " + ap;
document.getElementById("demo").innerHTML = dateString.toString();
Try This one.
JavaScript doesn't have functions to format the dates, so you'll have to do it manually. You can use this code for your first format:
<p id="demo"></p>
<script>
var d = new Date(2016, 5, 21);
document.getElementById("demo").innerHTML = getMonthName(d.getMonth()) + " " + d.getDate();
function getMonthName(month) {
var monthnames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
return monthnames[month];
}
</script>
You can add the code to do any other format you want. However, you'll quickly realize the reason why we have many libraries for that purpose. So, don't reinvent the wheel and just use one of those libraries.

Java script function to Add one hour to the "DD/name of the month/YYYY HH:MM:SS" format

I have a date format like this 15/name of the month/2016 Hr:MM:SS this is coming to me as a string. I want to add one hour to the input string and display it as Local time.
I am trying to substring this but the format is not consistent as the name of the month has many characters in "November" and with "July".
Can any one please suggest how to to with this.. I am looking at regular expressions but i am not sure if reg helps...
The following will allow you to add one hour and convert to local time.
var dateString = "15/January/2016 23:59:59";
// Replace slashes
var dateStringReplaced = dateString.replace('/', ' ');
// Parse date
var date = new Date(Date.parse(dateStringReplaced));
// Add an hour
date.setHours(date.getHours() + 1);
console.log(date.toLocaleString());
https://jsbin.com/tecosovaki/1/edit?js,console
function UTCTime() {
var time = "MM/DD/YYYY HH:MM:SS AM\PM";
var months = ["Jan", 'Feb', "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var array = dtc_time.split(/[\/\s:]/);
var d = new Date(array[2], array[0] - 1, array[1], array[3], array[4], array[5], 0);
d.setHours(array[3] - 1);
var time = formatAMPM(d);
var local = d.getDate() + "/" + months[d.getMonth()] + "/" + d.getFullYear() + " " + time;
document.getElementById("demo").innerHTML = local.fontcolor("white");
}
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
seconds = seconds < 10 ? '0' + seconds : seconds;
var strTime = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
return strTime;
}

Show clock with CST time in html page using JavaScript

How to show clock with CST time format in HTML page using JavaScript? It should show exact CST time in this format "02 Jul 2015 10:34:45 PM"
Not sure if there is a better way but i was unable to find anything. This works though.
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sept", "Oct", "Nov", "Dec"
];
d = new Date();
//set the offset
var utcOffset = -6;
//get utc
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
//create new date adjusting by the utcOffset to get local date/time
var localDate = new Date(utc + (3600000 * (utcOffset+1)));
//check if one character if so format as two by adding leading 0.
var formatDay = (localDate.getDate().length > 1) ? localDate.getDate() : '0' + localDate.getDate();
//string everything together
var fullDate = formatDay + ' ' + monthNames[localDate.getMonth()] + ' ' + localDate.getFullYear() + ' ' + localDate.toLocaleTimeString();
$('#div1').html(fullDate);
http://jsfiddle.net/ojga6a5u/

Changing YYYY-MM-DD and 24 Hour Clock to a Formatted DateTime

I have a webservice that returns the time as follows:
2015-04-22 15:09 // this is a string
I want to convert it to the following format:
TUE APR 21, 2015 7:50 AM
Is there any date formatting function in JavaScript?
Two aspects to this:
Parsing that string to a date
Formatting the date
There are lots of date formatting libraries available for JavaScript, since the specification doesn't provide any formatting routines. MomentJS is one of them, but there are several.
But not using a library:
Parsing the string
If you replace the space in the string you're receiving with the letter T, you can parse it with new Date(...) because then it will be in the date/time format specified in ES5. However, there's a problem: ES5 got the format wrong. They based it on ISO-8601, but said that if there was no timezone indicator, code should act as though timezone Z (UTC/GMT) were specified. That's wrong; ISO-8601 says no timezone indicator means "local time." In ES6, they're changing the spec to match ISO-8601, but that means we're now in a situation where some implementations (current Firefox) do the ES5 thing, and others (current Chrome) do the ES6/ISO-8601 thing. (try it here) sigh Result? You can't trust what you get back if there's no timezone indicator on it.
If you know the value you're being given is UTC, it's really easy to parse: Change the space to a T and add a Z to the end:
var dt = new Date(str.replace(" ", "T") + "Z");
If you know it's meant to be "local" time, you have to parse it as though it were UTC, then add on the timezone offset:
var dt = new Date(str.replace(" ", "T") + "Z");
dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset());
I think that still works correctly on DST boundaries, but you'll want to test.
Formatting the string
Is there any date formatting function in JavaScript?
No, all you get is the default toString (the format of which is not specified by the specification) and toISOString which outputs in YYYY-MM-DDThh:mm:ssZ format.
You do get methods that give you the individual parts (either in local time [e.g., getHours] or in UTC [e.g., getUTCHours]).
Various examples:
// The string
var str = "2015-04-22 15:09";
// Get the date
var dt = new Date(str.replace(" ", "T"));
// Hours, minutes, seconds
snippet.log("Hours: " + dt.getHours());
snippet.log("Minutes: " + dt.getMinutes());
snippet.log("Seconds: " + dt.getSeconds());
// Day, month, year -- note that months start at 0
snippet.log("Day of month: " + dt.getDate());
snippet.log("Month: " + dt.getMonth()); // 3 = April
snippet.log("Year: " + dt.getFullYear());
// UTC stuff
snippet.log("Hours UTC: " + dt.getUTCHours());
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
There is no date formatter in Javascript, however you can create custom date string from date object as following:
var day_names = new Array("SUN", "MON", "TUE", "WED",
"THU", "FRI", "SAT");
var month_names = new Array("JAN", "FEB", "MAR", "APR", "MAY",
"JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC");
var date = new Date();
var curr_day = date.getDay();
var curr_date = date.getDate();
var curr_month = date.getMonth();
var curr_year = date.getFullYear();
var cur_hour = date.getHours();
var minutes = date.getMinutes();
var AMorPM = cur_hour >= 12 ? AMorPM = "PM" : AMorPM = "AM";
cur_hour = cur_hour > 12 ? cur_hour -= 12 : cur_hour;
if (cur_hour < 10) cur_hour = "0" + cur_hour;
if (minutes < 10) minutes = "0" + minutes;
var finalDate = "<b>" + day_names[curr_day] + " " +
month_names[curr_month] + " " + curr_date + ", " +
curr_year + " " + cur_hour + ":" + minutes + " " +
AMorPM + "</b>";
document.getElementById('dateTime').innerHTML = finalDate;
DEMO

Format date() to eee,dd MMM YYYY,hh:mm:ss in JavaScript

This is quite similar to Stack Overflow question Format a new Date() to EEE MMM dd HH:mm:ss zzz yyyy.
But here I need a date format something like:
"Fri, 23 May 2014, 09:03:29"
Any Suggestions?
Try this example. I hope it works!
var timeString = myDate.getFullYear() + '-' + (myDate.getMonth()+1) + '-'
+ myDate.getDate() + ' ' + myDate.getHours() + ':' + myDate.getMinutes() + ':'
+ myDate.getSeconds();
var d = new Date();
alert(d.toString().split("GMT")[0]);
Just split the GMT from your date object string
A function like this can solve the problem:
function formatDate(myDate) {
var abbrMonths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var abbrDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
function zeroPadding(val) {
return val.toString().length === 1 ? "0" + val : val;
}
return abbrDays[myDate.getDay()] + ", " + myDate.getDate() + " " + (abbrMonths[myDate.getMonth()]) +
" " + myDate.getFullYear() + ", " + zeroPadding(myDate.getHours()) + ":" +
zeroPadding(myDate.getMinutes()) + ":" + zeroPadding(myDate.getSeconds());
}
To get the formatted date just pass your date into the function like so:
var formattedDate = formatDate(new Date());
Moment is a plugin made especially for formatting and calculating dates. Perhaps it can also help you if you're looking on formatting dates in multiple ways.

Categories

Resources