extract date and time from datetime using javascript - javascript

My time format is given below
var time = "2013-08-07 20:53:35"
I need to get the date "2013-08-07" as 07.08.2013 and time "20:53:35" as 20:53:35.

To achieve that you should
first separate date and time using split(" ")
Then split() date by "-"
Use reverse() on the date array and join it using .
var time = "2013-08-07 20:53:35"
let arr = time.split(' ');
let date = arr[0].split('-').reverse().join('-');
let tm = arr[1]
console.log(date)
console.log(tm)

depending on how much of this you will be doing I would highly recommend look at moment.js. You can download from npm if a nodejs app or just use from a cdn if browser based javascript. Here is a sample:
var time = "2013-08-07 20:53:35"
var newdate = moment(time).format("DD.MM.YYYY");
var newtime = moment(time).format("HH:mm:ss");
document.writeln(newdate);
document.writeln(newtime);

You can do like this using core javascript
function formatDate(datetime) {
var date = new Date(datetime);
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var strTime = hours+':'+minutes+ ':' + seconds;
return ('0' + (date.getMonth()+1)).slice(-2) + "." +('0' + (date.getDate())).slice(-2) + "."+ date.getFullYear() + " " + strTime;
}
console.log(formatDate('2013-08-07 20:53:35'));
https://www.quackit.com/javascript/javascript_date_and_time_functions.cfm
http://jsfiddle.net/p2wLrov4/2/

Related

How can I convert timestamp to date format yyyy-MM-dd'T'HH:mm:ssXXX?

I would like to know if there's a way to convert a timestamp to yyyy-MM-dd'T'HH:mm:ssXXX date format?
I can convert it to ISO using toISOString but it add Z at the end of the string.
Thank you.
var d = new Date();
var datestring = d.getDate() + "-" +
(d.getMonth() + 1) + "-" +
d.getFullYear() + "-T " +
d.getHours() + ":" +
d.getMinutes();
If you really do not want to use an external library like moment.js (which i would strongly recommend), as you stated in your comment, you will have to implement a function for that yourself, as regular javascript does not provide a function for this (as far as i know).
You can create an object of javascripts built-in Date class from a unix timestamp by using
var unixTimestamp = 1566394163;
//multiply with 1000 as Date expects milliseconds
var date = new Date(unixTimestamp * 1000);
Then you could build the output string yourself, by using something along this
var dateString = "";
dateString += date.getUTCFullYear()+"-";
dateString += date.getUTCMonth()+"-";
dateString += ...
On the other hand, if the Z at the end of the string is the only thing that bothers you about the format provided by toISOString() as a workaround you could use its output and remove the last character of it
var dateString = date.toISOString();
var newDateString = dateString.substr(0, dateString.length -1);
Please try using below code to convert timestamp to date format.
var date = new Date(timestamp*1000);
var year = date.getFullYear();
var month = months_arr[date.getMonth()];
var day = date.getDate();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
Display date time in any format you want.

Javascript format date

I have a date string which coming from the db as follows
/Date(1469167371657)/
Is there any way to convert this date to following format using javascript
MM/DD/YYYY HH:MM
I've searched a lot but unble to find a solution
In plain javascript you have to write your own function for string format a date, for example for your string format:
var date = new Date(1469167371657);
function stringDate(date) {
var mm = date.getMonth()+1;
mm = (mm<10?"0"+mm:mm);
var dd = date.getDate();
dd = (dd<10?"0"+dd:dd);
var hh = date.getHours();
hh = (hh<10?"0"+hh:hh);
var min = date.getMinutes();
min = (min<10?"0"+min:min);
return mm+'/'+dd+'/'+date.getFullYear()+" "+hh+":"+min;
}
console.log(stringDate(date));
drier code version
var date = new Date(1469167371657);
function stringDate(date) {
return ("0" + (date.getMonth() + 1)).slice(-2)+'/'
+("0" + date.getDate()).slice(-2)+'/'
+date.getFullYear()+" "
+("0" + date.getHours()).slice(-2)+':'
+("0" + date.getMinutes()).slice(-2)
}
console.log(stringDate(date));
with pure js you can do the folowing
var d = new Date();
console.log(d.getMonth() + 1 + "/" + d.getDate() + "/" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes())
You can use - http://momentjs.com/ and have it done like:
moment(1469167371657).format('MM/DD/YYYY HH:MM')
You can do this with the following steps:
1) convert the timestamp to a date object.
var timestamp = "/Date(1469167371657)/"; // However you want to save whatever comes from your database
timestamp = timestamp.substr(timestamp.indexOf("(")+1); // gives 1469167371657)/
timestamp = timestamp.substr(0,timestamp.indexOf(")")); // gives 1469167371657
var d = new Date(timestamp);
2) set it to your format
function leadZero(i) {if(i < 10) {return "0"+i;} return i;} // Simple function to convert 5 to 05 e.g.
var time = leadZero(d.getMonth()+1)+"/"+leadZero(d.getDate())+"/"+d.getFullYear()+" "+leadZero(d.getHours())+":"+leadZero(d.getMinutes());
alert(time);
Note: the date / timestamp you provided is too high for javascript to understand, so this example will not work correclty
I believe that number is milliseconds so to convert it to date, you would do this:
var time = new Date().getTime();
var date = new Date(time);
alert(date.toString()); // Wed Jan 12 2011 12:42:46 GMT-0800 (PST)
var time=1469167371657;
var date = new Date(time);
alert(date.toString());

Get time from datetime format

I'm getting this date format from back-end: 1970-01-01T10:59:00Z
How can I get the time from it with JavaScript and put it in this input:
<input type="time" ng-model='content.time' />
Thanks for your help!
You could use the getHours(), getMinutes() and getSeconds() function and concatenate the values.
var result = document.getElementById("result");
var dateTime = new Date();
var hours = new Date().getHours();
var minutes = new Date().getMinutes();
var seconds = new Date().getSeconds();
result.innerHTML = hours + ":" + minutes + ":" + seconds;
<p id="result"></p>
var date = new Date($scope.content.time);
var converted = date.getHours() + ":" + date.getMinutes();
console.log(converted);
This might help you:
var dt = new Date();
var tm = dt.getUTCHours();
For UTC.
Also you can use:
new dt.getHours()
new dt.getMinutes()
var date = new Date("1970-01-01T10:59:00Z");
var converted = date.toLocaleString();
console.log(converted);
Then you'd just assign the converted value to the model.
With angular, and not just vanilla javascript/DOM manipulation, in your controller js:
var dateTime=<referenceToDataRetrievedFromBackEnd>;
/*Format the date you've retrieved*/
var hours = new Date().getHours();
var minutes = new Date().getMinutes();
var seconds = new Date().getSeconds();
var formattedTimeString=hours + ":" + minutes + ":" + seconds
/*This is the part that actual ties the retrieved and reformatted data to the view*/
$scope.content.time=formattedTimeString;
In your controller add this function
var parseDateTime = function (input) {
vars = input.split('T');
date = vars[0].split('-');
time = vars[1].split(':');
//return date in 'yyyy-MM-dd H:i:s'
return date[0] + '-' + date[1] + '-' + date[2] + ' ' + time[0] + ':' + time[1] + ':00';
}
Then you can use it with your datetime
var dateTime = DATE_RECEIVED_FROM_BACKEND;
$scope.content.time = parseDateTime(dateTime);
Hope this helps :)
place this code in the controller where after the data u receive from backend
var d = new Date("1970-01-01T10:59:09Z");//pass the object which have ur date
$scope.content.time=d.getHours() + ":" + d.getMinutes()+":"+ d.getSeconds();

convert xml date and time using javascript

I am pulling the some information from a stock feed. the time stamp for last update comes in like this:
2016-02-10 13:32:41
How do I format it to be like:
1:32:41pm
2/10/2016
Here is my variable declaration:
time = x[0].getElementsByTagName("LASTDATETIME")[0].childNodes[0].nodeValue;
You could turn the string into a valid javascript date and then use the date methods to display it how you want to. For example to turn it into a javascript date, split it into its parts and then assemble.
var dateAndtime = x[0].getElementsByTagName("LASTDATETIME")[0].childNodes[0].nodeValue;
var date = dateAndtime.split(' ')[0];
var time = dateAndtime.split(' ')[1];
var year = date.split('-')[0];
var month = date.split('-')[1]-1;
var day = date.split('-')[2];
var hour = time.split(':')[0];
var minute = time.split(':')[1];
var second = time.split(':')[2];
var d = new Date(year, month, day, hour, minute, second);
There is no need to create a Date, you can just parse and reformat the string. You have to parse the string anyway, reformatting without a Date is just more efficient.
// 2016-02-10 13:32:41 => m/dd/yyyy h:mm:ssap
function reformatDateString(s) {
var b = s.split(/\D/);
var ap = b[3] < 12? 'am':'pm';
var h = b[3]%12 || 12;
return h + ':' + b[4] + ':' + b[5] + ap +
'\n' + +b[1] + '/' + b[2] + '/' + b[0];
}
document.write(reformatDateString('2016-02-10 13:32:41').replace('\n','<br>'))
document.write('<br>');
document.write(reformatDateString('2016-12-09 03:02:09').replace('\n','<br>'))

Moment.js Get difference between two dates in the dd:hh:mm:ss format?

I am calculating the time until 11:59PM of the current day. Here is an example.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.js"></script>
<script>
setInterval(function() {
var now = moment();
var mid = moment();
mid = mid.endOf('day');
var diffHours = mid.diff(now, 'hours');
var diffMinutes = mid.diff(now, 'minutes');
var diffSeconds = mid.diff(now, 'seconds');
console.log(diffHours + "h " + diffMinutes + "m " + diffSeconds + "s");
}, 1000)
</script>
However, I was hoping it would show me a time such as 20h 13m 49s, instead I am getting 20h 1255m 73500s
I understand this is working as intended pretty much, but how can I achieve the format I am seeking?
You'll want to modify your now variable after each diff.
var hours = mid.diff(now, 'hours'); //Get hours 'till end of day
now.hours(now.hours() + hours);
var minutes = mid.diff(now, 'minutes');
Just for comparison, here's David Stampher's moment.js example from a comment on another answer giving the time until 23:59:59.999 "today" and the same functionality in plain JS:
// Moment.js version
var now = moment();
var mid = moment();
mid = mid.endOf('day');
var diff1 = moment.utc(moment(mid, "DD/MM/YYYY HH:mm:ss")
.diff(moment(now, "DD/MM/YYYY HH:mm:ss")))
.format("HH:mm:ss");
console.log('moment.js: ' + diff1);
// POJS version
var z = (n) => (n<10? '0' : '') + n;
var ms = new Date().setHours(23,59,59,999) - new Date();
var diff2 = z(ms/3.6e6|0) + ':' +
z(ms%3.6e6/6e4|0) + ':' +
z(ms%6e4/1e3|0);
console.log('plain js : ' + diff2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

Categories

Resources