I am using time-picker to get the time :
<div class="timePicker-container" >
<md-time-picker
className="end-time"
enable-date="false"
(whenChange)="timeSelectionChanged($event)"
[disabled]="systemlogsform.value.range==='relativerange'">
</md-time-picker>
</div>
And timeSelectionChanged is as shown below:
public timeSelectionChanged(momentTime) {
console.log('momentTime', momentTime._d)
}
This contains the below data:
Tue Jun 15 2021 00:17:32 GMT+0530 (India Standard Time)
Now , how will I be able to get only the time part , i.e. 00:17:32 ?
You can convert into Date format and get hours , minutes and seconds from there.
getOnlyTime(dateTimeFormat)
{
let newFormat = new Date(dateTimeFormat);
let hr = newFormat .getHours();
let mins = newFormat .getMinutes();
let secs = newFormat .getSeconds();
let timeOnly = hr + ":" + mins + ":" + secs;
return timeOnly;
}
You can call the method to retrieve the time.
let timeFormat = getOnlyTime(momentTime._d);
console.log(timeFormat);
I am not sure what package you are using to convert into the required format, but if you are using 'moment.js' package, you can take a look at this website
Link to moment.js ==> https://momentjs.com/
What you want to do is something like this:
var myDate = "2017-08-30T14:24:03";
console.log(moment(myDate).format("HH:mm")); // 24 hour format
console.log(moment(myDate).format("hh:mm")); // 12 hour format
console.log(moment(myDate).format("hh:mm a")); // use 'A' for uppercase AM/PM
console.log(moment(myDate).format("hh:mm:ss A")); // with milliseconds
const dt = "Tue Jun 15 2021 00:17:32 GMT+0530 (India Standard Time)"
const d = new Date(dt).toLocaleTimeString(undefined, {
timeZone: 'Asia/Kolkata'
})
console.log(d)
Related
Updated My Question
How to get total minutes of difference between two dates using pure JavaScript when
Condition (1):: Same month, same year but date changes
newDate: 18/10/2016 0:50
oldDate: 17/10/2016 23:05
Condition (2):: Last date of current month and 1st date of next month
newDate: 1/11/2016 0:50
oldDate: 31/10/2016 23:05
Condition (3):: Last date of year and 1st date of new year
newDate: 1/1/2017 0:50
oldDate: 31/12/2016 23:05
Note: Please have a look newDate and oldDate to understand the conditions.
Thanks
Since you don't want to use a library for parsing date strings, you can write a simple function such as:
// Parse date string in "Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)" format
function parseDate(s) {
// Split into tokens
var b = s.match(/\w+/g) || [];
var months = 'jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
// Determine offset in minutes
var offSign = /GMT+/.test(s)? -1 : 1;
var offset = b[8].substr(0,2)*60 + +b[8].substr(2,2);
// Create date, applying offset to minutes
var date = new Date(Date.UTC(b[3],
months.indexOf(b[1].toLowerCase()),
b[2],
b[4],
+b[5] + (offSign*offset),
b[6]));
return date;
}
var d = parseDate("Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)")
console.log('UTC: ' + d.toISOString() + '\n' +
'Local: ' + d.toLocaleString());
Completed My Requirements with the below pure JavaScript code
In my code starttime and endtime are
//var startTime = localStorage.getItem("starttime");
//var endTime = new Date();
Example Here.
var startTime = new Date("Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)");
var endTime = new Date("Sun Jan 1 2017 15:35:57 GMT+0530 (India Standard Time)");
var totalMiliseconds = endTime - startTime;
alert(totalMiliseconds);
//output:: 86400000
var totalSeconds = totalMiliseconds/1000;
alert(totalSeconds);
//output:: 86400
var totalMinuts = totalSeconds/60;
alert(totalMinuts);
//output:: 1440
var totalHours = totalMinuts/60;
alert(totalHours);
//output:: 24
And this fulfill my all 3 conditions.
Thank You For Your Support !!!
I'm looking for something like yyyy/MM/dd hh:mm:ss ffff
Date.now() returns the total of milliseconds (ex: 1431308705117).
How can I do this?
You can use the Date constructor which takes in a number of milliseconds and converts it to a JavaScript date:
var d = new Date(Date.now());
d.toString() // returns "Sun May 10 2015 19:50:08 GMT-0600 (MDT)"
In reality, however, doing Date(Date.now()) does the same thing as Date(), so you really only have to do this:
var d = new Date();
d.toString() // returns "Sun May 10 2015 19:50:08 GMT-0600 (MDT)"
You can use native JavaScript Date methods to achieve that or you can use a library like Moment.js.
It is a simple as:
moment().format('YYYY/MM/D hh:mm:ss SSS')
If you are going use a lot of date formatting/parsing in your application then I definitely recommend using it.
You can use Date().toISOString(), i.e.:
let d = new Date().toISOString();
document.write(d);
Output:
2022-02-04T17:46:16.100Z
Demo:
let d = new Date().toISOString();
document.write(d);
Simple
const DateNow = Date.now(); // 1602710690936
console.log(new Date(DateNow).toString()) // returns "Sun May 10 2015 19:50:08 GMT-0600 (MDT)"
function formatted_date()
{
var result="";
var d = new Date();
result += d.getFullYear()+"/"+(d.getMonth()+1)+"/"+d.getDate() +
" "+ d.getHours()+":"+d.getMinutes()+":"+
d.getSeconds()+" "+d.getMilliseconds();
return result;
}
console.log(formatted_date())
Output: "2015/5/10 22:5:26 429"
function millisecondsToHuman(ms) {
const seconds = Math.floor((ms / 1000) % 60);
const minutes = Math.floor((ms / 1000 / 60) % 60);
const hours = Math.floor(ms / 1000 / 60 / 60);
const humanized = [
pad(hours.toString(), 2),
pad(minutes.toString(), 2),
pad(seconds.toString(), 2),
].join(':');
return humanized;
}
function pad(numberString, size) {
let padded = numberString;
while (padded.length < size) padded = `0${padded}`;
return padded;
}
Step 1: use new Date() to get the date as JavaScript format as Sun Jul 12 2020 15:40:16 GMT+0800 (Singapore Standard Time)
var d = new Date()
Step 2: use .toString() to convert to string and .substr string method to convert the previous string to "Jul 12 2020" and get rid of the rest
var d2 = d.toString().substr(4, 11)
Step 3: use .slice method to add '/' between dat, month and year to get Jul / 12 / 2020
var d3 = d2.slice(0, 3) + ' /' + d2.slice(3, 6) + ' /' + d2.slice(6))
const formattedDate = () => {
d = new Date()
cd = num => num.toString().padStart(2, 0)
return d.getFullYear()+"/"+cd(d.getMonth() + 1)+"/"+cd(d.getDate()) +
" "+ cd(d.getHours())+":"+cd(d.getMinutes())+":"+
cd(d.getSeconds())+" "+d.getMilliseconds()
}
console.log(formattedDate) //returns "2022/11/01 03:00:36 777"
var date = new Date();
will get you an answer formatted like this: Sun May 10 2015 21:55:01 GMT-0400 (Eastern Daylight Time)
var d = new Date();
var n = d.toJSON();
will get you the answer formatted the way you were looking for it.
Here is a great explanation of all the ways to manipulate the Date object
I like the dataformat package:
you can install using:
npm i dataformat.
and you can use like that:
dateFormat(medicao.DataHora, 'UTC:HH:MM')
I need some help with converting unixtime to a specific format. Here is what I am currently working with:
var date = "2014-05-01";
var indexPie = Date.parse(date);
I need indexPie in yyyy-mm-dd format. What I do not understand is that when log
var newDate = new Date(indexPie);
The results is:
Wed Apr 30 2014 18:00:00 GMT-0600 (Mountain Daylight Time)
when it should be:
Thur May 01 2014 18:00:00 GMT-0600 (Mountain Daylight Time)
Why is new Date(indexPie) resulting in Apr 30 and how do I get my correct format of yyyy-mm-dd?
Any suggestions would be great. Thanks.
I resolved the issue with the following:
var date = new Date(indexPie);
var year = date.getUTCFullYear();
var month = date.getUTCMonth() + 1;
var day = date.getUTCDate();
var dateString = year + "-" + month + "-" + day;
You are expecting that the value in date variable: "2014-05-01" will be parsed as in local timezone, but actually it is parsed as in UTC.
You can convert the date from UTC to local timezone like this:
var newDate = new Date(indexPie + new Date().getTimezoneOffset() * 60000);
I am doing a check of two different date times to see if one is greater than the other:
Here is my (now) current date time: Thu Aug 01 2013 10:27:40 GMT-0500 (CDT)
And here is my date time that I am seeing if it is greater or less than: Thu Aug 01 2013 12:15:00 GMT-0500 (CDT) - (that should be 12:15 am by the way)
Here is my code:
var current_date_time = new Date();
var date_time_checking_against = new Date(date_segment[0], date_segment[1]-1, date_segment[2], time_segment[0], time_segment[1]);
Which comes out to Thu Aug 01 2013 12:15:00 GMT-0500 (CDT). And then I am doing a simple if check:
if(current_date_time >= date_time_checking_against){ }
This is not working as 10:27:40 is not after 12:15:00. But it should be, seeing as how both times are AM. I need to know if this is the right way, or if there is a way to change it to 24 hour format or add am pm in there somehow. Any help is greatly appreciated, let me know if you need more clarity.
Thanks!
EDIT:
Here is the date time array:
var date_time_str = date+' '+time;
date_time_str = date_time_str.split(' ');
["2013-08-01", "12:15", "am"] // result from split above
var date_segment = date_time_str[0].split('-');
var time_segment = date_time_str[1].split(':');
var date_time_checking_against = new Date(date_segment[0], date_segment[1]-1, date_segment[2], time_segment[0], time_segment[1]);
Given the following data sources, this is how you'd properly create the Date object for it...
date_time_str = ["2013-08-01", "12:15", "am"];
var date_segment = date_time_str[0].split('-');
var time_segment = date_time_str[1].split(':');
var date_time_checking_against = new Date(
date_segment[0], // year
date_segment[1]-1, // month of year
date_segment[2], // day of month
(time_segment[0]%12) + (date_time_str[2] == 'pm' ? 12 : 0), // hour of day
time_segment[1]); // minute of hour
console.log(new Date() >= date_time_checking_against); // true, we've already passed this time
function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0].substring(2), // get only two digits
month = datePart[1], day = datePart[2];
document.write(new Date(day+'/'+month+'/'+year));
}
formatDate ('2010/01/18');
When i print this i get Thu Jun 01 1911 00:00:00 GMT+0530 (India Standard Time) but the system is actually 3:42 P.M
Use the current date to retrieve the time and include that in the new date. For example:
var now = new Date,
timenow = [now.getHours(),now.getMinutes(),now.getSeconds()].join(':'),
dat = new Date('2011/11/30 '+timenow);
you must give the time:
//Fri Nov 11 2011 00:00:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11"));
//Fri Nov 11 2011 23:23:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11 23:23"));
What do you want? Just the time? Or do you want to define a format? Cu's the code expects this format for date: dd/mm/yyyy, changed this to yyyy/mm/dd
Try this:
function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0],
month = datePart[1], day = datePart[2],
now = new Date;
document.write(new Date(year+'/'+month+'/'+day+" " + now.getHours() +':'+now.getMinutes() +':'+now.getSeconds()));
}
formatDate ('2010/01/18')
Output:
Mon Jan 18 2010 11:26:21 GMT+0100
Passing a string to the Date constructor is unnecessarily complicated. Just pass the values in as follows:
new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10))
You're creating a Date() object with no time specified, so it's coming out as midnight. if you want to add the current date and time, create a new Date with no arguments and borrow the time from it:
var now = new Date();
var myDate = new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10),
now.getHours(), now.getMinutes(), now.getSeconds())
No need to strip the last two characters off the year. "2010" is a perfectly good year.