Javascript: Formatting datetime yields NaN results - javascript

I am trying to format a mysql datetime object in Javascript, but I only get NaN results.
The value from the database is for example this datetime object:
2015-08-27 21:36:03
In my JS I try to convert this object as follows:
var formattedDate = new Date(datetimeObj);
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes;
return date.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
How come that I when printing the variable, I get NaN/NaN/NaN 12:NaN?

Some browsers will not parse the string "2015-08-27 21:36:03" as a valid date. For best results, use a standard ISO date string, as in
2015-08-27T21:36:03Z

Try this:
<script>
var formattedDate = new Date("2015-08-27 21:36:03");
console.log(formatDate(formattedDate));
function formatDate(date)
{
var hours = date.getHours();
var minutes = date.getMinutes();
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes;
return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
</script>
Its the same code, just passed the input in your function..

Here you can find answer on your quetions, it something like this with RegEx
var dateString = "2010-08-09 01:02:03";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString);
var dateObject = new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);

Related

display current dates hours and minute

I am facing an issue in javascript dates. i want to do minutes and second from current date.
My code:
date = new Date();
currentdate = new Date();
newCurrent = GetFormattedDate(currentdate);
GetFormattedDate(date) {
hour = ("0" + (date.getHours())).slice(-2);
min = ("0" + (date.getMinutes())).slice(-2);
return hour + ":" + min; //output 18:43
}
expected output:
`18:00` //if minutes are 0 to 29 then show current hours reset the minutes again start with 0 like 18:00
`18:30` //if minutes are 29 to 59 then show current hours reset the minutes again start with 30 like 18:30
What should I do? anyone help me?
var d = new Date();
var myTime = d.getHours() +':'+ (d.getMinutes() <= 29 ? '00' : '30') ;
template string:
const d = new Date();
const myTime = `${d.getHours()}:${d.getMinutes() <= 29 ? '00' : '30'}` ;
or
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var altedMinutes = minutes <= 29 ? '00' : '30';
var displayTime = hours + ':' + altedMinutes;
If you want PM/AM
var suffix = 'AM'
var hours = now.getHours()
if (hours>11) {
hours - =12;
suffix = 'PM'
}
...
var displayTime = hours + ':' + altedMinutes + ' ' + suffix;

Convert integer time facebook message time - javascript

How to Covert This time to date time like " 08:45 PM "
json time code
{"time":1480797244,"short":false,"forceseconds":false}
i need covert this time (1480797244) need idea in jQuery or javascript
Use the below method to convert the timestamp to your required format. Check the Updated fiddle also
function formatAMPM(timestamp) {
date = new Date(timestamp * 1000)
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var year = date.getFullYear();
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = day + '/' + month + '/' + year + ' ' + hours + ':' + minutes + ' ' + ampm;
return strTime;
}
var timeObj = {"time":1480797244,"short":false,"forceseconds":false};
alert(formatAMPM(timeObj.time))

Add 5 minutes to current time javascript

I am getting the current date as below:
var now = new Date();
I want to add 5 minutes to the existing time. The time is in 12 hour format. If the time is 3:46 AM, then I want to get 3:51 AM.
function DateFormat(date) {
var days = date.getDate();
var year = date.getFullYear();
var month = (date.getMonth() + 1);
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = days + '/' + month + '/' + year + '/ ' + hours + ':' + minutes + ' ' + ampm;
// var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
function OnlyTime(date) {
var days = date.getDate();
var year = date.getFullYear();
var month = (date.getMonth() + 1);
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
// var strTime = days + '/' + month + '/' + year + '/ ' + hours + ':' + minutes + ' ' + ampm;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
function convertTime(time)
{
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if (AMPM == "PM" && hours < 12) hours = hours + 12;
if (AMPM == "AM" && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
alert(sHours + ":" + sMinutes);
}
function addMinutes(date, minutes) {
return new Date(date.getTime() + minutes * 60000);
}
function convertTime(time)
{
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if (AMPM == "PM" && hours < 12) hours = hours + 12;
if (AMPM == "AM" && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
alert(sHours + ":" + sMinutes);
}
// calling way
var now = new Date();
now = DateFormat(now);
var next = addMinutes(now, 5);
next = OnlyTime(next);
var nowtime = convertTime(next);
How to add 5 minutes to the "now" variable?
Thanks
You should use getTime() method.
function AddMinutesToDate(date, minutes) {
return new Date(date.getTime() + minutes * 60000);
}
function AddMinutesToDate(date, minutes) {
return new Date(date.getTime() + minutes*60000);
}
function DateFormat(date){
var days = date.getDate();
var year = date.getFullYear();
var month = (date.getMonth()+1);
var hours = date.getHours();
var minutes = date.getMinutes();
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = days + '/' + month + '/' + year + '/ '+hours + ':' + minutes;
return strTime;
}
var now = new Date();
console.log(DateFormat(now));
var next = AddMinutesToDate(now,5);
console.log(DateFormat(next));
//Date objects really covers milliseconds since 1970, with a lot of methods
//The most direct way to add 5 minutes to a Date object on creation is to add (minutes_you_want * 60 seconds * 1000 milliseconds)
var now = new Date(Date.now() + (5 * 60 * 1000));
console.log(now, new Date());
get minutes and add 5 to it and set minutes
var s = new Date();
console.log(s)
s.setMinutes(s.getMinutes()+5);
console.log(s)
Quite easy with JS, but to add a slight bit of variety to the answers, here's a way to do it with moment.js, which is a popular library for handling dates/times:
https://jsfiddle.net/ovqqsdh1/
var now = moment();
var future = now.add(5, 'minutes');
console.log(future.format("YYYY-MM-DD hh:mm"))
Try this:
var newDateObj = new Date();
newDateObj.setTime(oldDateObj.getTime() + (5 * 60 * 1000));
I'll give a very short answer on how to add any string of the form ny:nw:nd:nh:nm:ns where n is a number to the Date object:
/**
* Adds any date string to a Date object.
* The date string can be in any format like 'ny:nw:nd:nh:nm:ns' where 'n' are
* numbers and 'y' is for 'year', etc. or, you can have 'Y' or 'Year' or
* 'YEar' etc.
* The string's delimiter can be anything you like.
*
* #param Date date The Date object
* #param string t The date string to add
* #param string delim The delimiter used inside the date string
*/
function addDate (date, t, delim) {
var delim = (delim)? delim : ':',
x = 0,
z = 0,
arr = t.split(delim);
for(var i = 0; i < arr.length; i++) {
z = parseInt(arr[i], 10);
if (z != NaN) {
var y = /^\d+?y/i.test(arr[i])? 31556926: 0; //years
var w = /^\d+?w/i.test(arr[i])? 604800: 0; //weeks
var d = /^\d+?d/i.test(arr[i])? 86400: 0; //days
var h = /^\d+?h/i.test(arr[i])? 3600: 0; //hours
var m = /^\d+?m/i.test(arr[i])? 60: 0; //minutes
var s = /^\d+?s/i.test(arr[i])? 1: 0; //seconds
x += z * (y + w + d + h + m + s);
}
}
date.setSeconds(date.getSeconds() + x);
}
Test it:
var x = new Date();
console.log(x); //before
console.log('adds 1h:6m:20s');
addDate(x, '1h:6m:20s');
console.log(x); //after
console.log('adds 13m/30s');
addDate(x, '13m/30s', '/');
console.log(x); //after
Have fun!
This function will accept ISO format and also receives minutes as parameter.
function addSomeMinutesToTime(startTime: string | Date, minutestoAdd: number): string {
const dateObj = new Date(startTime);
const newDateInNumber = dateObj.setMinutes(dateObj.getMinutes() + minutestoAdd);
const processedTime = new Date(newDateInNumber).toISOString();
console.log(processedTime)
return processedTime;
}
addSomeMinutesToTime(("2019-08-06T10:28:10.687Z"), 5)
Add minutes into js time by prototype
Date.prototype.AddMinutes = function ( minutes ) {
minutes = minutes ? minutes : 0;
this.setMinutes( this.getMinutes() + minutes );
return this;
}
let now = new Date( );
console.log(now);
now.AddMinutes( 5 );
console.log(now);

Remove trailing zeroes in date in JavaScript

I am using the current format in order to product a JavaScript date:
var date = visitdate;
var newdate = date.split("/").reverse().join("-");
I would expect this to return 1900-01-01 for example, however what this actually returns is 1900-01-0100.
Iv'e tried using slice in order to trim this off but this just ends up slicing off the day instead and still adds the zeros. There seems to be no way of getting rid of them. Is there anyway to remove them?
You may write a function like below and whatever format needed you can change
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
hours = hours < 10 ? '0'+hours : hours;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
var Month = date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1;
var Date = date.getDate() < 10 ? '0'+date.getDate() : date.getDate();
var strDate = Month + "/" + Date + "/" + date.getFullYear();
return strDate + " " + strTime;
}
Or in your case if you dont want time just remove strTime from return of function
Assuming the input is "01/01/1900 00:00" - add a .split(" ") in between like this:
"01/01/1900 00:00".split(" ")[0].split("/").reverse().join("-");
Or just skip the reverse() if your input is like you said "1900-01-01":
"1900/01/01 00:00".split(" ")[0].split("/").join("-");
You could also extract the information from your date string by using a regex like this:
var d = '1990/01/01 00:00';
var matches = d.match(/^(\d+)\/(\d+)\/(\d+) (\d+):(\d+)$/);
if(matches){
var year = matches[1]
, month = matches[2]
, day = matches[3]
, hour = matches[4]
, minutes = matches[5];
console.log(year+'-'+month+'-'+day);
}

Getting the current date and time and appending it to a string

I need to create strings in javascript that contain the current time.
How can I create two strings like the following, but with the current timestamp?
itemTimestamp = "Itemized at 2014-05-01, 11:11 PM"
itemFilename = "itemized_at_2014_05_01_11_11_pm.png"
JSFIDDLE:
http://jsfiddle.net/gkQ7y/9/
function format(date) {
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
hours = hours < 10 ? '0' + hours : hours; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime ="Itemized at "+year+"-"+month+"-"+day+", "+hours + ':' + minutes + ' ' + ampm;
return strTime;
}
var d = new Date();
document.getElementById("test1").innerHTML = format(d);
var replaced = format(d).replace(/[ :-]/g,"_").replace(",","");
document.getElementById("test2").innerHTML = replaced+".png";

Categories