Date/Time format issue with Chrome - javascript

I get the date/time value as below in JSON:
"ChangedDate":"\/Date(1349469145000)\/"
In FF and IE, I get the above date in 12 hr format (10/5/2012 - 3:32:25 PM) using the helper function below:
Handlebars.registerHelper('FormatDate', function (date) {
if (date == null)
return "";
else {
var value = new Date(parseInt(date.substr(6)));
return value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear() + " - " + value.toLocaleTimeString();
}
});
however, in Chrome I still get the 24 hr format (10/5/2012 - 15:32:25).
How do I get the date/time value in 12 hr format in Chrome?

Use toLocaleTimeString when the intent is to display to the user a
string formatted using the regional format chosen by the user. Be
aware that this method, due to its nature, behaves differently
depending on the operating system and on the user's settings.
You may be better off changing this line:
return value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear() + " - " + value.toLocaleTimeString();
to:
return value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear() + " - " + (value.getHours() > 12 ? value.getHours() - 12 : value.getHours()) + ":" + value.getMinutes() + ":" + value.getSeconds();
Where we check to see if the hours are > 12 and if so we subtract 12 from that number.
(value.getHours() > 12 ? value.getHours() - 12 : value.getHours())
So your example 15:32:25 would be 15 - 12 = 3: 3:32:25.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getSeconds
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getMinutes
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getHours
EDIT
//set up example
var date = new Date("10/5/2012");
date.setHours(15,32,25,00);
//Get data from date
var month = date.getMonth()+1;
var day = date.getDate();
var year = date.getFullYear();
var hours = date.getHours();
var amOrPm = "AM";
if(date.getHours() > 12){
hours = date.getHours() - 12;
amOrPm = "PM";
}
var minutes = date.getMinutes();
if(minutes < 10)
minutes = "0" + minutes;
var seconds = date.getSeconds();
if(seconds < 10)
seconds = "0" + seconds;
var dateString = month + "/" + day + "/" + year + " - " + hours + ":" + minutes + ":" + seconds;
console.log(dateString);
I made this example a bit more detailed than needed, but it helps to show you what's going on. Hope it helps.
EXAMPLE
Condensed down this would look something like:
//Get data from date
var dateString = (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + " - " + (date.getHours() > 12 ? date.getHours() - 12 : date.getHours())+ ":" + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":" + (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()) + " " + (date.getHours() > 12 ? "PM" : "AM");
EXAMPLE

Related

get 24 hours date and time for loop in javascript

I have one drop-down(values are "Last 24 hours", "Last 48 hours", etc like) when I select "Last 24 hours" in the drop-down
i need all dates from now to yesterday with one hour intervals.
i tried this,
var todayDate = new Date();
if(type=="hours"){ // for hours based drop-down
var oneDayAgo = new Date(todayDate.getTime());
oneDayAgo.setDate(todayDate.getDate() - 1);
console.log("oneDayAgo"+oneDayAgo);
var hours = todayDate.getHours();
for(var i = hours; i <= hours+24; i++) {
if(i<25){
var newHours=i;
var newDates=todayDate.getFullYear() + "-" + ("00" + (todayDate.getMonth() + 1)).slice(-2) + "-" + ("00" + todayDate.getDate()).slice(-2) + " " + ("00" +newHours).slice(-2) + ":" + ("00" + todayDate.getMinutes()).slice(-2) + ":" + ("00" + todayDate.getSeconds()).slice(-2);
console.log(newDates);
}else{
var newHours=i-24;
var newDates=oneDayAgo.getFullYear() + "-" + ("00" + (oneDayAgo.getMonth() + 1)).slice(-2) + "-" + ("00" + oneDayAgo.getDate()).slice(-2) + " " + ("00" +newHours).slice(-2) + ":" + ("00" + oneDayAgo.getMinutes()).slice(-2) + ":" + ("00" + oneDayAgo.getSeconds()).slice(-2);
console.log(newDates);
}
}
}
my expected output is ,
for example current date and time is 2014-04-27 13:07 means,
output like 2014-04-27 13:07, 2014-04-27 12:07, 2014-04-27 11:07 , 2014-04-27 10:07.... 2014-04-26 13:07
please help on this. thanks
function getDateItems(hours) {
var toDate = new Date();
var fromDate = new Date();
fromDate.setTime(fromDate.getTime() - (hours * 60 * 60 * 1000));
var result = [];
while (toDate >= fromDate) {
result.push(toDate.getFullYear() + "-" + ("00" + (toDate.getMonth() + 1)).slice(-2) + "-" + ("00" + toDate.getDate()).slice(-2) + " " + ("00" + toDate.getHours()).slice(-2) + ":" + ("00" + toDate.getMinutes()).slice(-2) + ":" + ("00" + toDate.getSeconds()).slice(-2));
// consider using moment.js library to format date
toDate.setTime(toDate.getTime() - (1 * 60 * 60 * 1000));
}
return result;
}
var datesFrom24Hours = getDateItems(24);
var datesFrom48Hours = getDateItems(48);
console.log(datesFrom24Hours);
Here a working sample, which might be what you want.
//get type and hoursOption from dropdowns
var type = 'hours'
var hoursOption = 48;
var todayDate = new Date();
if(type=="hours"){ // for hours based drop-down
var hours = todayDate.getHours();
for(var i = hours; i <= hours + hoursOption; i++) {
todayDate.setHours(todayDate.getHours() - 1)
var newDates = todayDate.getFullYear() + "-" + ("00" + (todayDate.getMonth() + 1)).slice(-2) + "-" + ("00" + todayDate.getDate()).slice(-2) + " " + ("00" + todayDate.getHours()).slice(-2) + ":" + ("00" + todayDate.getMinutes()).slice(-2) + ":" + ("00" + todayDate.getSeconds()).slice(-2);
console.log(newDates);
}
}
For for-loop variable hours I added hourOption which comes from dropdown options, eg. 24, 48, 72, etc.
Inside loop you take todayDate and just add one hour less then before, so it will show hours counting backwards.
This worked for me
const start = new Date("2022-01-01T00:00:00");
const end = new Date("2022-01-01T23:00:00");
for (let current = start; current <= end; current.setHours(current.getHours() + 1)) {
console.log(current);
}

How to format database datetime in javascript?

I have a datetime value gotten from an SQLServer database table:
2016-08-16T17:00:00Z
Using javascript, I want to format the date as follow:
16/08/2016 17:00:00
I have used the code below:
$scope.FormatDate = function (value) {
if (value !== null && typeof (value) !== 'undefined') {
var date = new Date(value);
var returnStr = date.getDate() + "/" + date.getMonth() + 1 + "/" + date.getFullYear();
return returnStr;
} else {
return value;
}
}
The result from the sample resource is:
17/71/2016
I want your help to get the output result as: "16/08/2016 17:00:00"
If all you want to do is format it then you don't need to create an actual date object, you can do a simple string replace using a regex to grab the individual parts, as per this simple demo:
var value = "2016-08-16T17:00:00Z";
console.log(value.replace(/(\d{4})-(\d\d)-(\d\d)T([^Z]+)Z/,"$3/$2/$1 $4"));
In the context of your function:
$scope.FormatDate = function (value) {
if (value !== null && typeof (value) !== 'undefined') {
return value.replace(/(\d{4})-(\d\d)-(\d\d)T([^Z]+)Z/,"$3/$2/$1 $4");
} else {
return value;
}
}
Another solution:
var parsed = Date.parse("2016-08-16T17:00:00Z"),
date = new Date(parsed),
day = date.getUTCDate(),
month = date.getUTCMonth() + 1,
year = date.getUTCFullYear(),
hour = date.getUTCHours(),
minute = date.getUTCMinutes(),
second = date.getUTCSeconds(),
dateStr = "";
day = day < 10 ? "0" + day : day;
month = month < 10 ? "0" + month : month;
hour = hour < 10 ? "0" + hour : hour;
minute = minute < 10 ? "0" + minute : minute;
second = second < 10 ? "0" + second : second;
dateStr = day + "/" + month + "/" + year + " " + hour + ":" + minute + ":" + second;
console.log(dateStr);
Updated: The old code may change across countries, because they have different local date/time format, so I have updated to format it explicitly.
Try this
function formatDate(date)
{
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
minutes = minutes < 10 ? '0'+minutes : minutes;
seconds = seconds < 10 ? '0'+seconds : seconds;
var strTime = hours + ':' + minutes + ':' +seconds ;
return date.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
You can use this library to format the date as you desire with implementing some logic.
http://momentjs.com/
Just work with the function parameter value and use moment.
Example:
const date = moment("2016-08-16T17:00:00Z").date();
const month = moment("2016-08-16T17:00:00Z").month();
const hour = moment("2016-08-16T17:00:00Z").hour();
const year = moment("2016-08-16T17:00:00Z").year();
const minute = moment("2016-08-16T17:00:00Z").minute();
const sec = moment("2016-08-16T17:00:00Z").second();
// implementing some logic
console.log('' + date + '/' + month + '/' + year + ' ' + hour + ':' + minute + ':' + sec);
here is the fiddle:
https://jsfiddle.net/Refatrafi/6m4m7mp3/

Get HTML5 datetime-local exact value

Try to use this, http://jsfiddle.net/mdg2u4ut and you will notice the hour will be different with what you've set, like in my case
I think it's because of the timezone problem.
I can just hardcoded -8 for the hour variable in my case but that's not the smart way of doing it.
<input type="datetime-local" onblur="formatDate(this.value)" />
<p id="para"></p>
my JS
function formatDate(date) {
if(date){
date = new Date(date);
var hours = date.getHours();
var minutes = date.getMinutes();
var format = hours < 12 ? 'AM' : 'PM';
hours = hours % 12;
hours = hours ? hours : 12; // making 0 a 12
minutes = minutes < 10 ? '0'+minutes : minutes;
var time = hours + ':' + minutes + ' ' + format;
var output = date.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + time;
document.querySelector('#para').innerHTML = output;
}
}
Use getUTC methods instead. jsFiddle
var hours = date.getUTCHours();
var minutes = date.getUTCMinutes();
var format = hours < 12 ? 'AM' : 'PM';
hours = hours % 12;
hours = hours ? hours : 12; // making 0 a 12
minutes = minutes < 10 ? '0'+minutes : minutes;
var time = hours + ':' + minutes + ' ' + format;
var output = date.getUTCMonth()+1 + "/" + date.getUTCDate() + "/" + date.getUTCFullYear() + " " + time;

Date range according to month in jquery?

Well i am trying to display a date range in the container header on click of button.ON the click of the button it takes the value of it and displays it.
var date = new Date,day = date.getDate(),month = date.getMonth() + 1,
year = date.getFullYear(),hour = date.getHours(),minute = date.getMinutes(),
seconds = date.getSeconds(),ampm = hour > 12 ? "PM" : "AM";
hour = hour % 12;
hour = hour ? hour : 12;
minute = minute > 9 ? minute : "0" + minute;
seconds = seconds > 9 ? seconds : "0" + seconds;
hour = hour > 9 ? hour : "0" + hour;
date = month + "/" + (day-6) + "/" + year + " " + hour + ":" + minute + " " + ampm + " - " + month + "/" + day + "/" + year + " " + hour + ":" + minute + " " + ampm;
// date holds in the format "12/16/2011 08:14 PM"
$('#panelid').text(date); //panelid is where date range will be shown
As i was working on this code after 10th i didn't face this problem but now day range becomes something like
this : 2/-5/2014 11:51 AM - 2/1/2014 11:51 AM
How can i remedy this? Any suggestion.

Get local Date string and time string

I am trying to get the LocaleDateString and the LocaleTimeString which that would be toLocaleString() but LocaleString gives you GMT+0100 (GMT Daylight Time) which I wouldn't it to be shown.
Can I use something like:
timestamp = (new Date()).toLocaleDateString()+toLocaleTimeString();
Thanks alot
You can use the local date string as is, just fiddle the hours, minutes and seconds.
This example pads single digits with leading 0's and adjusts the hours for am/pm.
function timenow() {
var now = new Date(),
ampm = 'am',
h = now.getHours(),
m = now.getMinutes(),
s = now.getSeconds();
if (h >= 12) {
if (h > 12) h -= 12;
ampm = 'pm';
}
if (m < 10) m = '0' + m;
if (s < 10) s = '0' + s;
return now.toLocaleDateString() + ' ' + h + ':' + m + ':' + s + ' ' + ampm;
}
console.log(timenow());
If you build up the string using vanilla methods, it will do locale (and TZ) conversion automatically.
E.g.
var dNow = new Date();
var s = ( dNow.getMonth() + 1 ) + '/' + dNow.getDate() + '/' + dNow.getFullYear() + ' ' + dNow.getHours() + ':' + dNow.getMinutes();

Categories

Resources