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
Related
I want to use the following script to refresh the time every second. Works fine, but I want it to output the format like this:
October 06 - 13:38:04.
How do you do that?
var timestamp = '<?=time();?>';
function updateTime(){
const firstOption = {month: 'long', day: 'numeric'};
const secondOptions = { hour: 'numeric', minute: 'numeric', second: 'numeric' };
$('#time').html(new Date(timestamp).toLocaleDateString("en-NL", firstOption) + " - " + new Date(timestamp).toLocaleTimeString("en-NL", secondOptions));
timestamp++;
}
$(function(){
setInterval(updateTime, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="time"></p>
Try this:
const firstOption = {month: 'long', day: 'numeric'};
const secondOptions = { hour: 'numeric', minute: 'numeric', second: 'numeric' };
$('#time').html(new Date(timestamp).toLocaleDateString("en-NL", firstOption) + " - " + new Date(timestamp).toLocaleTimeString("en-NL", secondOptions));
Read more about it here.
Simple function for formating your date.
function dateToString(/* add timestamp parameter if you want */) {
var d = new Date(/* timestamp parameter here */);
var months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'October',
'November',
'December',
]
var month = months[d.getMonth() - 1];
var date = (d.getDate() < 10) ? "0" + d.getDate() : d.getDate();
var hours = d.getHours(),
minutes = d.getMinutes(),
seconds = d.getSeconds();
var time = (hours < 10 ? "0" + hours : hours) + ':' + (minutes < 10 ? "0" +
minutes : minutes) + ':' + (seconds < 10 ? "0" + seconds : seconds);
return month + ' ' + date + ' - ' + time;
}
dateToString(/* pass timestamp argument here */);
Afaik PHP's time function return a unix timestamp and you're looking for an ES5 solution. This might help you.
const datetime = 1601984483;
var padStart = function(str, length) {
while (str.toString().length < length)
str = "0" + str;
return str;
}
var format = function (timestamp) {
var date = new Date();
var d = {
M: date.toLocaleString('default', { month: 'long' }),
d: padStart(date.getDate(), 2),
h: padStart(date.getHours(), 2),
m: padStart(date.getMinutes(), 2),
s: padStart(date.getSeconds(), 2)
};
return [[d.M, d.d].join(' '), [d.h, d.m, d.s].join(':')].join(' ');
}
console.log(format(datetime));
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>
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.
Good day,
I've been using the following time function JS in an HTML code. I'm still in the progress of learning and understanding JS and been playing around with it. However, I recently noticed that whenever my minutes are less than 10, the 0 is taken away, say 14:5 instead of 14:05. Is there quick format way to fix this?
Thanks in advance, here's the JS function
function updateClock() {
var now = new Date(),
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
time = now.getHours() + ':' + now.getMinutes();
date = [now.getDate(),
months[now.getMonth()],
now.getFullYear()].join(' ');
// set the content of the element with the ID time to the formatted string
// document.getElementById('time').innerHTML = [date, time].join(' ');
document.getElementById('time').innerHTML = ["Today is", date, "and the time is", time].join(' ');
setTimeout(updateClock, 1000);
}
updateClock();
You should be able to check if your minutes value is less than 10 and append a 0 to the front of it :
// If the minutes are greater than 10, pad them with a '0'
time = now.getHours() + ':' + (now.getMinutes() < 10 ? '0' : '') + now.getMinutes();
Example
You can see a working example here and demonstrated below :
As far as I know, there is no built-in method for this. However, you can use a ternary operator to add the 0 when necessary.
var mins = now.getMinutes();
var minsFixed = mins < 10 ? '0' : '' + mins;
time = now.getHours() + ':' + minsFixed;
Just use one more format function like this and call it everywhere:
function zero(num) {
return num < 10 ? '0' + num : num;
}
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