How to format database datetime in javascript? - 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/

Related

Formatting time error - "10.03" becomes "10.3"

I have a date and time that I format. It works most of the time, but if the time has a "0" in the second last space it will return wrong. For example, time "10.30" will be formatted correctly, but "10.03" will return "10.3" without the zero.
My code:
const today: Date = new Date();
const date: Date = new Date(item.receivedDateTime);
let time: string;
if (date.getFullYear() === today.getFullYear() &&
date.getMonth() === today.getMonth() &&
date.getDate() === today.getDate()) {
time = date.getHours() + ":" + date.getMinutes();
} else {
time = date.getDate() + "/" + (date.getMonth() + 1);
}
Above will format time incorrectly. What is wrong in the code? I prefer not to use padstart as it is not supported in IE11 or moment.js.
You can save the value of date.getMinutes() in a variable and check if it's smaller than 10, and if so, append a 0.
const minutes = date.getMinutes();
const formattedMinutes = (minutes < 10) ? '0' + minutes : minutes;
Finally, use the formatted value for output:
time = date.getHours() + ":" + formattedMinutes;
You can use a simple pad function
const pad = num => ("0"+num).slice(-2);
const item = {"receivedDateTime":1570000000000}
const today = new Date();
const date = new Date(item.receivedDateTime);
let time = "";
if (date.getFullYear() === today.getFullYear() &&
date.getMonth() === today.getMonth() &&
date.getDate() === today.getDate()) {
time = pad(date.getHours()) + ":" + pad(date.getMinutes());
} else {
time = pad(date.getDate()) + "/" + pad(date.getMonth() + 1);
}
console.log(time)
Instead of,
time = date.getHours() + ":" + date.getMinutes();
You can use,
var minutes = d.getMinutes() > 9 ? d.getMinutes() : '0' + d.getMinutes();
time = date.getHours() + ":" + minutes

Why this code got an Uncaught TypeError

I want to get next day and format it into "yyyy-MM-dd HH:mm" format, but when I run this in chrome's console, I got an Uncaught TypeError: date.getHours is not a function, why? The nextDay variable is clearly an instance of Date.
But when I removed hour and minute, just kept year, month and date, it successed, can anyone tell me the reason?
var time = new Date().getTime();
var interval = 24 * 60 * 60 * 1000;
var nextDay = new Date(time + interval);
function padding(number) {
return number < 10 ? "0" + number : "" + number;
}
function format(date) {
var year = date.getFullYear(),
month = date.getMonth(),
date = date.getDate(),
hour = date.getHours(),
minute = date.getMinutes();
return padding(year) + "-"
+ padding(month + 1) + "-"
+ padding(date) + " "
+ padding(hour) + ":"
+ padding(minute);
}
console.log(format(nextDay));
Your function takes a parameter named "date" and then tries to declare a local variable named "date". That declaration will be ignored, and the initializer will just overwrite the value of the parameter.
Change the name of the parameter:
function format(d) {
var year = d.getFullYear(),
month = d.getMonth(),
date = d.getDate(),
hour = d.getHours(),
minute = d.getMinutes();
return padding(year) + "-"
+ padding(month + 1) + "-"
+ padding(date) + " "
+ padding(hour) + ":"
+ padding(minute);
}
You are using the same variable name as the parameter, date is used twice, change the variable name like down below.
var time = new Date().getTime();
var interval = 24 * 60 * 60 * 1000;
var nextDay = new Date(time + interval);
function padding(number) {
return number < 10 ? "0" + number : "" + number;
}
function format(date) {
var year = date.getFullYear(),
month = date.getMonth(),
theDate = date.getDate(), //change the variable name
hour = date.getHours(),
minute = date.getMinutes();
return padding(year) + "-"
+ padding(month + 1) + "-"
+ padding(date) + " "
+ padding(hour) + ":"
+ padding(minute);
}
console.log(format(nextDay));

Javascript Date Object - Different Value in JSFiddle

This is a simple one I think.
Why do I get 2015-11-04 when I run the following code in JSFiddle (new Date(1451606399999), but when I run the same code in my browser console I get 2015-12-31 (which is the value I'm expecting).
I would have thought any in either case the timezone would be the same as the code is running on the client, and why would timezone make more than a month difference in the date?
function test()
{
var date = new Date(1451606399999);
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDay();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
var formattedTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
document.getElementById("myDiv").innerHTML = formattedTime;
}
JSFiddle with code
Confusingly, date.getMonth() is 0 based, meaning 0 is January, so it should be month = date.getMonth()+1. Also confusingly date.getDay() actually returns the day of the week (0 is Sunday, 1 is Monday... etc). The function you're looking for is date.getDate()
function test(){
var date = new Date(1451606399999);
var year = date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
var formattedTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(date);
document.getElementById("myDiv").innerHTML = formattedTime;
}

Convert timestamp from am/pm to 24-hour in Javascript

I'm using jquery timepicker. On user side, time needs to be displayed as am/pm format (10:30am or 5:30pm). I need to append that value to datepicker value.
For example, if datepicker value is 07/08/2015, final value should be 07/08/2015 17:30.
Problem here is in converting 5:30pm to 17:30. How to do it with javascript
You could write your own conversion function that converts time-strings with "pm" in them by adding 12 hours, like so:
var convertTimeStringTo24Hours = function(timeString) {
if (timeString.match(/pm$/)) {
var match = timeString.match(/([0-9]+):([0-9]+)pm/);
var hours = parseInt(match[1]) + 12;
var minutes = match[2];
return hours + ':' + minutes;
} else {
return timeString.replace('am', '');
}
};
In case you want to convert from the 12 Hour system(hh:mm:ssPM/AM) to 24 Hour system then you could use the following
function timeConversion(s) {
const timeString = s.toString()
if (timeString.match(/PM$/)) {
var match = timeString.match(/([0-9]+):([0-9]+):([0-9]+)PM/)
var hours = parseInt(match[1]) + 12;
var minutes = match[2];
var second = match[3]; parseInt(match[1])
if (parseInt(match[1]) === 12) {
return parseInt(match[1])+ ':' + minutes + ':' + second;
} else {
return hours + ':' + minutes + ':' + second;
}
} else {
var match = timeString.match(/([0-9]+):([0-9]+):([0-9]+)AM/)
var hours = parseInt(match[1]);
var minutes = match[2];
var second = match[3];
if (hours === 12) {
return '00:' + minutes + ':' + second;
} else {
return timeString.replace('AM', '');
}
}
}

Date/Time format issue with Chrome

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

Categories

Resources