Format date in javascript with time [duplicate] - javascript

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 9 years ago.
How would I format a date in javascript in the format: June 2, 2013, 1:05 p.m.
Here is a relevant link, but I'm still having trouble getting this exact formatting, based on Date(). http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3

Why not write a function to get bits of the date for you and return an Object which lets you build a string as easily as string concatenation of Object properties.
The example below will always base answer on UTC time
var easyDate = (function () {
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
thstndrd = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'];
return function (d) {
var dow = d.getUTCDay(),
dom = d.getUTCDate(),
moy = d.getUTCMonth(),
y = d.getUTCFullYear(),
h = d.getUTCHours(),
m = d.getUTCMinutes(),
s = d.getUTCSeconds();
return {
dom: '' + dom,
th: thstndrd[dom % 10],
day: days[dow],
moy: '' + (moy + 1),
month: months[moy],
year: '' + y,
ampm: h < 12 ? 'a.m.' : 'p.m.',
hh: h < 10 ? '0' + h : '' + h,
sh: '' + (h % 12 || 12),
mm: m < 10 ? '0' + m : '' + m,
ss: s < 10 ? '0' + s : '' + s,
};
};
}());
var o = easyDate(new Date());
// Object {dom: "2", th: "nd", day: "Sunday", moy: "6", month: "June"…}
o.month + ' ' + o.dom + ', ' + o.sh + ':' + o.mm + ' ' + o.ampm;
// "June 2, 8:43 p.m."

This should be useful to you: http://blog.stevenlevithan.com/archives/date-time-format

i would suggest moment.js. here it is: http://momentjs.com/
import it and do this
moment().format('LLL');
this is what you want

At w3schools you can find a complete reference to Javascript's Date object
Then you can use the methods to combine into a string of your liking.
var d = new Date();
d.getHours() + ":" + ...
There isn't a method to get the month name, you will need to get the number and create a switch.
The hour is in 24h format, so you have to convert and calculate if it is am or pm.
The day and year you can get directly using getDate() and getFullYear()
References
w3schools
MDN

Related

JS: Formatting ISO Date String to Custom Format?

I have an ISO Date string such as "2020-08-12T03:02:47Z". I want to convert these to "August 12, 2020 3:02PM". Would I have to concert it to a timestamp and work backwards to accomplish this?
you should look at the moment.js package
npm i moment
console.log(moment(yourVariable).format('LLLL'))
https://momentjs.com/docs/
You can use formatting options of the Internationalization API. For instance like this:
let fmt = new Intl.DateTimeFormat('en-US', {
dateStyle: "long",
timeStyle: "short",
timeZone: "UTC",
hour12: true
});
// Demo
let str = fmt.format(new Date("2020-08-12T03:02:47Z"));
console.log(str); // "August 12, 2020 at 3:02 AM"
// Optional: when you don't like the "at" or the space before "AM" or "PM":
str = str.replace(/ (..)$| at\b/g, "$1");
console.log(str); // "August 12, 2020 3:02AM"
You had to build a new date and from this get the values and reformat them.
For month use an array. For the hours get AM/PM and the hours (0-12/0-11 = 0-23). For the 2-digit minutes add before a string "0" and get than the last 2 chars. For hours you could even so but you show us hours as 1-digit.
const MONTH = ['January,', 'February', 'March', 'April', 'May', 'June', 'JUly', 'August', 'September', 'October', 'November', 'December'];
let date = new Date ('2020-08-12T03:02:47Z');
let time = date.getHours();
let hours = (time<13) ? time : time % 12;
let amPm = hours >= 12 ? 'PM' : 'AM'
date = MONTH[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear() + ' ' + hours + ':' + ('0' + date.getMinutes()).slice(-2) + amPm;
console.log(date);
Ciao, try to use moment suing format 'LLL'. Like this:
let date = '2020-08-12T03:02:47Z'
console.log(moment(date).format('LLL'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

Fixed date to be use for date conversion

Is there a way I can have a fixed date that I will use for conversion.
as you can see, the code below states that it is the time in Manila, PH but when you open it given that you are in a different timezone to me it will give you different time. Date(); will just get the time in your computer.
Is there a way to get a date which will be use as a default date so that I can add or minus hours to get my desired conversion date even though it will be open in different timezones?
function showTime() {
var a_p = "";
var today = new Date();
var curr_hour = today.getHours();
var curr_minute = today.getMinutes();
var curr_second = today.getSeconds();
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var myDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var date = new Date();
var day = date.getDate();
var month = date.getMonth();
var thisDay = date.getDay(),
thisDay = myDays[thisDay];
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;
if (curr_hour < 12) {
a_p = "<span>AM</span>";
} else {
a_p = "<span>PM</span>";
}
if (curr_hour == 0) {
curr_hour = 12;
}
if (curr_hour > 12) {
curr_hour = curr_hour - 12;
}
curr_hour = checkTime(curr_hour);
curr_minute = checkTime(curr_minute);
curr_second = checkTime(curr_second);
document.getElementById('clock-large1').innerHTML=curr_hour + " : " + curr_minute + " : " + curr_second + " " + a_p;
document.getElementById('date-large1').innerHTML="<b>" + thisDay + "</b>, " + day + " " + months[month] + " " + year;
}
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
setInterval(showTime, 500);
<div id="clockdate-full">
<div class="wrapper-clockdate1">
<div id="clock-large1"></div>
<div id="date-large1"></div>
<div id="timezone">Manila, PH</div>
</div>
</div>
Checkout moment .js
http://momentjs.com
You can specify the time zone of the date time
var timezone = 'America/Chicago'
moment().tz(timezone).format('hh:mm:ss z')
If you can't use an external link, you should try the code below:
var opt= {
timeZone: 'America/Chicago',
year: 'numeric', month: 'numeric', day: 'numeric',
hour: 'numeric', minute: 'numeric', second: 'numeric'
},
formatDate = new Intl.DateTimeFormat([], opt)
formatDate.format(new Date())
Is there a way to get a date which will be use as a default date so that I can add or minus hours to get my desired conversion date even though it will be open in different timezones?
Yes, just specify the "fixed" date in a suitable format. Most browsers will parse ISO 8601 extended format strings like 2017-05-25T17:35:48+08:00. That represents 5:30pm in Manilla, which is UTC+08:00.
To get the equivalent time on the user's system:
var d = new Date('2017-05-25T17:35:48+08:00');
console.log(d.toString()); // equivalent local time
If you want to support browsers like IE 8, you'll need to parse the string manually or use a library with a parser, e.g. moment.js or fecha.js.

Pikaday date formatting without Moment.js

I'm using Pikaday, which requires Moment.js to format dates. This allows easy date formatting:
var picker = new Pikaday({
format: 'YYYY-MM-DD'
});
However, when I include the Pikaday npm package, Moment.js is over 40kb. Literally all I need it for is to change the date format to YYYY-MM-DD from the practically unusable default Pikaday format.
Can I do this without having to include a 40kb library?
If you want to use only format YYYY-MM-DD, you can build the date string using native Date methods:
const picker = new Pikaday({
field: document.getElementById('datepicker')
,onSelect: date => {
const year = date.getFullYear()
,month = date.getMonth() + 1
,day = date.getDate()
,formattedDate = [
year
,month < 10 ? '0' + month : month
,day < 10 ? '0' + day : day
].join('-')
document.getElementById('datepicker').value = formattedDate
}
})
Demo
const picker = new Pikaday({
field: document.getElementById('datepicker')
,onSelect: date => {
const year = date.getFullYear()
,month = date.getMonth() + 1
,day = date.getDate()
,formattedDate = [
year
,month < 10 ? '0' + month : month
,day < 10 ? '0' + day : day
].join('-')
document.getElementById('datepicker').value = formattedDate
}
})
#import url("https://rawgit.com/dbushell/Pikaday/master/css/pikaday.css");
<script src="https://rawgit.com/dbushell/Pikaday/master/pikaday.js"></script>
<input type="text" id="datepicker">
I wrote a small formatter a while ago after seeing the date-formatter.js formatter and parser, maybe it will suit. It's pretty much self–documenting:
function formatDate(date, format) {
var tokens = ['d', // day number, e.g. 3, 12
'dd', // day number padded to two digits, e.g. 03, 12
'ddd', // day name abbreviated, e.g. Mon, Tue
'dddd', // day name in full, e.g. Monday, Tuesday
'M', // month number, e.g. 5, 10
'MM', // month number padded to two digits, e.g. 05, 10
'MMM', // month name abbreviated, e.g. May, Oct
'MMMM', // month name in full, e.g. May, October
'y', // Year, e.g. 71, 2011
'yy', // Year as two digits, e.g. 71, 11
'yyy', // Year as three digits, e.g. 071, 011
'yyyy', // Year padded to 4 digits, e.g. 0071, 2011
'h', // Hour, e.g. 1, 12
'hh', // Hour padded to two digits, e.g. 01, 12
'm', // Minute, e.g. 1, 23
'mm', // Minute padded to two digits, e.g. 01, 23
's', // Second, e.g. 1, 15
'ss', // Second padded to two digits, e.g. 01, 15
'ap', // 12 hour time lower case, e.g. 1:45 am, 12:30 pm
'AP', // 12 hour time upper case, e.g. 1:45 AM, 12:30 PM
'z', // Return values and "z" timezone
'Z', // Return values and "Z" timezone
'tz', // Append timezone as +/-00:00
'TZ']; // Append timezone as +/-00:00
var months = ['January','February','March','April','May','June','July',
'August','September','October','November','December'];
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'];
// Generate all the parts as strings
var parts = {d : '' + date.getDate(),
dd : ('0' + date.getDate()).slice(-2),
ddd : days[date.getDay()].slice(0,3),
dddd : days[date.getDay()],
M : '' + (date.getMonth() + 1),
MM : ('0' + (date.getMonth() + 1)).slice(-2),
MMM : months[date.getMonth()].slice(0,3),
MMMM : months[date.getMonth()],
y : '' + date.getFullYear(),
yy : ('0' + date.getFullYear()).slice(-2),
yyy : ('00' + date.getFullYear()).slice(-3),
yyyy : ('000' + date.getFullYear()).slice(-4),
h : '' + date.getHours(),
hh : ('0' + date.getHours()).slice(-2),
m : '' + date.getMinutes(),
mm : ('0' + date.getMinutes()).slice(-2),
s : '' + date.getSeconds(),
ss : ('0' + date.getSeconds()).slice(-2)};
// Parse format character by character and build string
var b = format.split('');
var formattedString = '';
var token = '';
for (var i = 0, iLen = b.length; i < iLen; i++) {
token += b[i];
if (tokens.indexOf(token + b[i+1]) == -1) {
if (tokens.indexOf(token) != -1) {
formattedString += parts[token];
} else {
formattedString += token;
}
token = '';
}
// console.log(token + ' : ' + formattedString);
}
return formattedString;
}
['yyyy-MM-ddThh:mm:ss',
'yyyyMMTddhhmm',
'dddd, d MMMM, yyyy at hh:mm:ss'
].forEach(function (s) {
document.write('<br>' + formatDate(this, s));
}, new Date());
Try this if you're using /uglify or other compilers this might work better for you.
onSelect: function(date) {
//Format here
}
Instead of
onSelect: date => {
//Format here
}
you can also do the following
new Pikaday({
field: document.getElementById('eDate'),
toString: function(date) {
var parts = [('0'+date.getDate()).slice(-2), ('0'+(date.getMonth()+1)).slice(-2), date.getFullYear()];
return parts.join("-");
}
})
this will produce 18-07-1980. You can change from '-' to '/' by changing return parts.join("-"); and you can rearrange parts to apply mm/dd/yyyy via parts array

How to find ordinal position of any given weekday in JavaScript

I'm trying to find the actual position of a weekday in constant time. I get it working with loop but trying to find out it with some Mathematics. I know it is like divide it by 7 but not getting it work.
Here is the code.
for(var ind=0; ind<=between.length; ind++){
if (new Date(between[ind]).getMonthWeek() === baseDtWk && new Date(between[ind]).getDay() === baseDtD) {
datesToBeMarked.push(between[ind]);
console.log(" :Date: " + between[ind] + " :Week: " + new Date(between[ind]).getMonthWeek());
console.log("Date entered : " + new Date(between[ind]));
}
}
I have done this few days back. It is as simple as the code below. :)
On fiddle.
Number.prototype.nth= function(){
var n= Math.round(this), t= Math.abs(n%100), i= t%10;
if(i<4 && (t<4 || t> 20)){
switch(i){
case 1:return n+'st';
case 2:return n+'nd';
case 3:return n+'rd';
}
}
return n+'th';
}
Date.prototype.nthofMonth= function(){
var today= this.getDate(),m=this.getMonth(),
day= ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday'][this.getDay()],
month= ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'][m];
return [(m+1)+'-'+today,'the ', Math.ceil(today/7).nth(), day, 'of', month, 'in', this.getFullYear()].join(' ');
}
var date=new Date().nthofMonth();
console.log(date);
You haven't shown how you want the result to look, I guess you want to know if a particular date is, say, the nth Tuesday, e.g.
// Add ordinal to a number
function addOrdinal(n) {
var ord = [,'st','nd','rd'];
var a = n % 100;
return n + (ord[a>20? a%10 : a] || 'th');
}
// Return the ordinal number of a day in the month
function ordinalDay(d) {
d = d || new Date();
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday', 'Friday','Saturday'];
return addOrdinal(Math.ceil(d.getDate()/7)) + ' ' + days[d.getDay()];
}
console.log(ordinalDay(new Date(2015,0,1))); // 1st Thursday
console.log(ordinalDay(new Date(2015,0,27))); // 4th Tuesday
console.log(ordinalDay(new Date(2015,0,31))); // 5th Saturday
console.log(ordinalDay(new Date(2015,11,25))); // 4th Friday

Alternative to toLocaleString() for chrome browser

function tolocal(str)
{
var date, split, dSplit, tSplit, d, raw;
date = '';
split = str.split(' ');
if (split.length === 2) {
dSplit = split[0].split('-');
tSplit = split[1].split(':');
}
raw = d.toLocaleString().split(' GMT')[0];
return raw.substring(raw.indexOf(", ")+2, raw.lastIndexOf(':')) + " " + raw.substring(raw.length-2,raw.length)
}
The above code, works well in ie browser where I get the output in the following format.
November 13,2012 10:15 AM
But I am not able to achieve the same in the chrome browser. Is there any other function which will help me achieve the same output? date.toUTCString() provides the same result but I am not sure how different it is to toLocaleString() in terms of functionality.
Thanks in advance.
Just do it manually:
// Where "date" is a Date object
function dateFormatUTC(date) {
var months = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
var hours = date.getUTCHours();
if (hours < 10) hours = '0' + hours;
var minutes = date.getUTCMinutes();
if (hours < 10) hours = '0' + hours;
var monthName = months[date.getUTCMonth()];
var timeOfDay = hours < 12 ? 'AM' : 'PM';
return monthName + ' ' + date.getUTCDate() + ', ' +
date.getUTCFullYear() + ' ' + hours + ':' + minutes + timeOfDay;
}
maybe you can use a thirdparty library to do stuff like that: moment.js is a good one.
Example:
moment(d).format('MMMM Do, YYYY h:mms a');
you can try using options like below:
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// request a weekday along with a long date
var options = {weekday: "long", year: "numeric", month: "long", day: "numeric"};
// an application may want to use UTC and make that visible
options.timeZone = "UTC";
options.timeZoneName = "short";
alert(date.toLocaleString("en-US", options));
Please find the reference #
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

Categories

Resources