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));
Related
How can i convert the date i get from DB to a certain format.?
this is what I get, 2021-03-30T17:57:53.489Z
I want it to be in format of dd/mmm/yyyy hh:mm in my localtime.
expected output : 30/03/2021 11:27 PM
what I tried so far,
const formatDate = (date) => {
let data = new Date(date);
data = data.toLocaleString('rm-CH', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
return data;
};
console.log(formatDate('2021-03-30T17:57:53.489Z'))
on jsfiddle i get the output like "30-03-2021 23:27"
but on my React native app, when I try this I get output like Tue mar 30 23:27:53 2021.
can someone help me out here.?
PS: My Timezone is India, GMT +5.30. the date string is what I get from my DB(create_date, Postgresql)
A one-liner with fancy string manipulation (spread out to make more readable):
console.log(
new Date()
.toISOString()
.replace(/-/g, '/')
.replace('T', ' ')
.split(':')
.slice(0, -1)
.join(':')
.split(' ')
.map((a, i) => i === 0 ? a.split('/').reverse().join('/') : a)
.join(' ')
);
Or you could just calculate it manually:
const date = new Date(),
pad = (num) => num.toString().length < 2 ? `${'0'.repeat(2 - num.toString().length)}${num}` : num;
console.log(
`${pad(date.getDate())}/${pad(date.getMonth())}/${date.getFullYear()} ${pad(date.getHours())}:${pad(date.getMinutes())}`
);
Or take a shortcut and use a library like Moment.
console.log(
moment().format('DD/MM/yyyy HH:mm')
);
<script src="https://momentjs.com/downloads/moment.js"></script>
I actually figured out a way,
function formatDate() {
var d = new Date('2021-03-30T17:57:53.489Z'),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear(),
hour = d.getHours(),
min = d.getMinutes();
var ampm = hour >= 12 ? 'pm' : 'am';
hour = hour % 12;
hour = hour ? hour : 12; // the hour '0' should be '12'
min = min < 10 ? '0'+min : min;
var strTime = hour + ':' + min + ' ' + ampm;
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return `${day}-${month}-${year} ${strTime}`
}
output : 30-03-2021 11:27 pm
This question already has answers here:
How to add 30 minutes to a JavaScript Date object?
(29 answers)
Closed 2 years ago.
I am facing an issue in javascript dates. I want to display previous and after 30min
How should I added previous or after 30min in current dates.
this.setState({
current: new Date().toLocaleTimeString(), //10:30:02 PM
slotTime: new Date().toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit'
}), //10:30 AM
Output:
10:30 AM //current date
expected:
10:00 AM //previous
10:30 AM //current
11:00 AM //after 30min
anyone help me?
You can simply do it like this:
var currDate = new Date();
var dd = new Date().setMinutes(currDate.getMinutes() - 30); //reduce 30 minutes
var ddPLus = new Date().setMinutes(currDate.getMinutes() + 30); //add 30 minutes
var reductedTime = new Date(dd);
var addedTime = new Date(ddPLus);
console.log("Current time: ", new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })) //current time
console.log("Reduced time: ", reductedTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })) // reduced time by 30mins
console.log("Added time: ", addedTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })) // added time by 30mins
Hope this help
/* required:
* - timestamp => number of timestamp format
* - format => return format, ex. format 1 (23:59:59), format 2 (23:59)
* return: time with string
*/
function timestampToTime(timestamp, format = 1) {
if (!isNaN(timestamp) || timestamp != undefined) {
let dd = new Date(timestamp)
if (format == 1) {
return ('00' + dd.getHours()).slice(-2) + ':' + ('00' + dd.getMinutes()).slice(-2) + ':' + ('00' + dd.getSeconds()).slice(-2)
} else if (format == 2) {
return ('00' + dd.getHours()).slice(-2) + ':' + ('00' + dd.getMinutes()).slice(-2)
}
} else {
return null
}
}
let dd = + new Date()
let previous = timestampToTime(dd - (1.8e+6)) // 1.8e+6 = 30 min
let current = timestampToTime(dd)
let after = timestampToTime(dd + (1.8e+6)) // 1.8e+6 = 30 min
console.log(previous)
console.log(current)
console.log(after)
I have a perfectly functioning clock.js widget that I'm using to display date and time on multiple displays throughout our offices in several states.
The offices in the Eastern timezone have no issue, as this defaults to eastern time (our server running the screens for every display is eastern).
However, I want to add a conditional in here (say if $screenID == 3 {... so that on the screens in the Central time zone it shows the proper central time.
How should I go about adding a block in here for that condition to show central rather than eastern?
function startTime() {
var today = new Date();
var hr = today.getHours();
var min = today.getMinutes();
// var sec = today.getSeconds();
ap = (hr < 12) ? "<span>AM</span>" : "<span>PM</span>";
hr = (hr == 0) ? 12 : hr;
hr = (hr > 12) ? hr - 12 : hr;
//Add a zero in front of numbers<10
hr = checkTime(hr);
min = checkTime(min);
// sec = checkTime(sec);
document.getElementById("clock").innerHTML = hr + ":" + min + " " + ap;
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var curWeekDay = days[today.getDay()];
var curDay = today.getDate();
var curMonth = months[today.getMonth()];
// var curYear = today.getFullYear();
var date = curWeekDay+", "+curDay+" "+curMonth;
document.getElementById("date").innerHTML = date;
var time = setTimeout(function(){ startTime() }, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
Use timezones.
function startTime(screen, loc) {
var timeZone = "America/Chicago";
if (screen === 1)
timeZone = "America/New_York";
var dateOptions = { weekday: 'long', day: 'numeric', month: 'long', timeZone: timeZone };
var timeOptions = { hour: 'numeric', minute: 'numeric', timeZone: timeZone };
var dt = new Date();
document.getElementById("myclock" + loc).innerHTML = dt.toLocaleString("en-US", timeOptions);
document.getElementById("mydate" + loc).innerHTML = dt.toLocaleString("en-NZ", dateOptions);
}
startTime(0, 1);
startTime(1, 2);
<div id="myclock1">asdf</div>
<div id="mydate1">asdf</div>
<hr>
<div id="myclock2">asdf</div>
<div id="mydate2">asdf</div>
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.
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