I am trying to get the time of device. The code I am using is like this -
const estimatedDeviceTimeMs = new Date().getTime();
alert(new Date(estimatedDeviceTimeMs));
The result of above code is Thu Jul 30 2020 12:01:54 GMT+0530 (India Standard Time).
I need to take out 12:01:54 in a variable and GMT+0530 in another variable if possible.
toTimeString return the time. Then split by space to get time and timezone like below:
var date = new Date();
console.log(date.toTimeString().split(" ")[0]);
console.log(date.toTimeString().split(" ")[1]);
Try this out
let date = new Date();
let time = date.toTimeString().split(' ')[0];
let gmt = date.toTimeString().split(' ')[1];
console.log(`Time is ${time} and GMT is ${gmt} `);
In Bangla if you need it
const parts = new Date().toLocaleTimeString('bn-in',{timeZoneName:'long'}).split(" ");
console.log(parts)
const estimatedDeviceTime = parts.slice(0,1) + " " +parts.slice(2)
console.log(estimatedDeviceTime)
You can call it by specific
const time = new Date();
console.log(`${time.getHours()}:${time.getMinutes()}:${time.getSeconds()}`);
Related
I'm working on an appointment booking React app where a teacher can set their virtual office hours in the form of a time slot.
let availability = ["09:00", "17:00"]; // from 9 AM to 5 PM local time
Since this time is local to the teacher, I'd like to store it as UTC time in the ISO 8601 format so that if a student is in a different region, I can parse it on the client and show this time in their appropriate timezone.
I tried using the parse function from date-fns#2.22.1 like this
parse('09:00', 'HH:mm', new Date()); // => Wed Jan 01 0020 00:00:00 GMT-0456 (Eastern Daylight Time)
But, this didn't return the time in my timezone (Central Standard Time).
Is there a way to represent this local time slot in UTC?
Not sure if this is your desired output
const inputTime = "09:00";
const outputDate = new Date(new Date().toJSON().slice(0, 10) + " " + inputTime).toUTCString();
console.log(outputDate);
I came to a solution which was inspired by #Anas Abdullah Al. Here are two simple functions which will convert from both UTC and a user's local time.
const format = window.dateFns.format;
const convertLocalToUTC = (localTime) => {
if (!localTime) {
throw new Error("Time can't be empty");
}
return new Date(`${new Date().toJSON().slice(0, 10)} ${localTime}`)
.toISOString()
.slice(11, 16);
};
const convertUTCToLocal = (UTCTime) => {
if (!UTCTime) {
throw new Error("Time can't be empty");
}
const currentUTCDate = new Date().toISOString().substring(0, 10);
const inputUTCDateTime = `${currentUTCDate}T${UTCTime}:00.000Z`;
return format(new Date(inputUTCDateTime), "HH:mm");
};
const UTCTime = "14:00";
const localTime = "09:00";
console.log(convertLocalToUTC(localTime)); // 14:00 UTC
console.log(convertUTCToLocal(UTCTime)); // 09:00 CST
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/2.0.0-alpha0/date_fns.min.js"></script>
Hope this helps someone else.
I am using angular material datepicker
https://material.angular.io/components/select/overview
but this returns only the date and not the current time :
Mon May 28 2018 00:00:00 GMT+0530 (IST)
Is there any way I can get the current time also from this?
You can use the ngModelChange to parse the date before setting it to your model, I recommend you momentJS for easy date manipulations.
in the HTML
<input [ngModel]="date" (ngModelChange)="onDataChange($event)" matInput [matDatepicker]="picker" placeholder="Choose a date">
In your Component.ts
onDataChange(newdate) {
const _ = moment();
const date = moment(newdate).add({hours: _.hour(), minutes:_.minute() , seconds:_.second()})
this.date = date.toDate();
console.log({hours: _.hour(), minutes:_.minute() , seconds:_.second()})
}
you can find the full solution here https://stackblitz.com/edit/angular-ecq2lc
Right now the material date picker provides just the current date (without the current time), but there is an open issue in the official repo, so we might see a time picker in the near future.
The angular material is not providing Time right now you need to manually get time from timeStamp, Try this -
function getTimeFromDate(timestamp) {
let date = new Date(timestamp * 1000);
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
return hours+":"+minutes+":"+seconds
}
let timeStamp = new Date("Mon May 28 2018 00:00:00 GMT+0530 (IST)")
console.log(getTimeFromDate(timeStamp));
For Example currenttime = Mon May 28 2018 00:00:00 GMT+0530 (IST)
Currenttime is an example if u using current date means just use new Date()
//Sample function calling Method
Exacttime(){
this.functionName = this.diffhours(new(currenttime))
}
diffhours(currenttime){
var diff = new Date(currenttime);
diff .getHours(); // => 9
diff .getMinutes(); // => 30
diff .getSeconds(); // => 51
}
How to get date time from this /Date(1518696376959)/ in javascript?
I have tried like this
var d = new Date("1519192874994");
I have tried like this var d = new Date("1519192874994");
No need to wrap it in quotes, Date constructor will takes millisecond value (Number)
var d = new Date(1519192874994) //Wed Feb 21 2018 11:31:14 GMT+0530 (India Standard Time)
From "/Date(1518696376959)/"
Make it
var str = "/Date(1518696376959)/";
var date = new Date( +str.match(/\d+/g)[0] ); //notice the unary plus after getting the match
I'm comparing two dates; one returned as a UTC String (as part of an Ajax response) and the second in local browser time:
Basically, I want to see if the date returned (endTime) happened before right now. My code is below and I thought I had it right but it's not working.
var isActive = true;
var buffer = 30000; // 30 seconds
var endTime = new Date(Date.parse(response.endTime)); // Fri Oct 23 2015 12:01:14 GMT-0400 (EDT)
var now = new Date(); // Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)
var nowUtc = new Date(now).toUTCString(); // "Fri, 23 Oct 2015 00:01:31 GMT"
var nowTimeMs = new Date(nowUtc).getTime(); // 1445558491000
var endTimeMs = endTime.getTime() + buffer; // 1445616104000
if( nowTimeMs > endTimeMs ){
isActive = false;
}
isActive should remain as true but instead it's false. I feel like I've been looking at this too long and am missing something very simple. Am I?
Thanks for any helpful tips.
Update:
Based on the responses I thought I'd update my question. What is the best way to compare two dates where one is this:
new Date(); // Thu Oct 22 2015 21:51:53 GMT-0400 (EDT)
...and the other is a String representation of date:
"2015-10-23 01:49:27"
I figure the best way to create a valid Date object out of the String is using this code.
isThisActive:function(p){
var isActive = true;
var buffer = 30000;
var pEndTime = myObj.parseStringAsDate(p.callEndTime);
var now = new Date();
var offset = now.getTimezoneOffset() * 60000;
now.setTime( now.getTime() + offset );
var nowTimeMs = now.getTime();
var endTimeMs = pEndTime.getTime() + buffer;
if( nowTimeMs > endTimeMs ){
isActive = false;
}
return isActive;
},
parseStringAsDate:function(str){
var dateTimeStr = str.split(" ");
var dateStr = dateTimeStr[0].split("-");
var year = dateStr[0];
var month = dateStr[1];
var day = dateStr[2];
var timeStr = dateTimeStr[1].split(":");
var hours = timeStr[0];
var minutes = timeStr[1];
var seconds = timeStr[2];
return new Date( year,month,day,hours,minutes,seconds);
}
Because "pEndTime" is in UTC I applied the offset to the "now" Date object but even this is not working. Where's the problem here? I thought this would solve it.
SOLVED:
The latest code I posted did work. I was just getting incorrect values for the response.endTime (It wasn't converted to correct military time). Thank you everyone for your input. I've tried to upgrade as many helpful responses as I could.
You should not use the Date constructor or Date.parse (which do the same thing) to parse date strings. Either write your own parse function (below) or use a well maintained library.
To parse the format in the OP, you can use:
// Parse Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)
function parseMMMDY(s) {
var b = s.split(/\W/);
var months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};
var sign = /GMT-\d{4}/i.test(s)? 1 : -1;
var min = +b[5] + (sign * b[8].slice(0,2) * 60 ) + (sign * b[8].slice(-2));
return new Date(Date.UTC(b[3], months[b[1].toLowerCase().slice(0,3)], b[2], b[4], min, b[6]));
}
document.write(parseMMMDY('Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)'));
I think the problem is here:
var endTime = new Date(Date.parse(response.endTime));
respnonse.endTime is UTC, right? But when you parse it to Date value, Date.parse assumes it is in local timezone (GMT-0400 as in your example code). It means that the endDate gets the wrong value
I usually use moment.js in my projects which related to formatting date time, especially in the reports (I'm working in the field of finance). You must have one more library in your project but it provides many other functionalities
Sorry, this is for your new update. I haven't got enough 'population' to leave a comment :P
var endTime = new Date(Date.parse(response.endTime)); // Fri Oct 23 2015 12:01:14 GMT-0400 (EDT)
var now = new Date(); // Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)
Your endTime doesn't seem to return a UTC date as you mentioned. It looks to be using (EDT) so maybe you didn't have to convert it to UTC.
I have date like this 25. 02. 2014 18:48:21 and I'm trying to convert it into timestamp
var someDate = '25. 02. 2014 18:48:21';
var timestamp = new Date(someDate).getTime();
but it's returning NaN since I moved files to a new domain, what can be a problem?
'25. 02. 2014 18:48:21' is not a valid date format. You'll have to convert it with regex first, like that:
var someDate = '25. 02. 2014 18:48:21';
var converted = someDate.replace(/^(\d{2}\. )(\d{2}\. )(\d{4})/, '$3. $2$1');
// converted is in format: YYYY. MM. DD.
var timestamp = new Date(converted).getTime();
Running this within the console, creating a new date with that variable gives me Invalid Date. Trying switching around the 25. and 02. like so:
var someDate = '02. 25. 2014 18:48:21';
var timestamp = new Date(someDate).getTime(); // 1393372101000
The format should be "Month, Day, Year, Time".
Switching month and day will work. I also removed the dots.
var date = "25. 02. 2014 18:48:21";
new Date(date.replace(/(\d{2})\. (\d{2})\./, '$2 $1'))
// Tue Feb 25 2014 18:48:21 GMT+0100 (W. Europe Standard Time)
you can try something like below (if your string has always same format)
var someDate = '25. 02. 2014 18:48:21';
var arr = someDate.split(' ');
var time = arr[3].split(':');
var timeStamp = new Date(arr[2],arr[1].split('.')[0],arr[0].split('.')[0],time [0],time[1],time[2]).getTime();
It uses javascript date object constructor
var d = new Date(year, month, day, hour, minute, seconds);
which works across all browsers
function convertSomeDate(str){
var d= str.match(/\d+/g),
dA= [d[2], '-', d[1], '-', d[0], 'T', d[3], ':', d[4], ':', d[5], 'Z'].join('');
return +new Date(dA)
}
var someDate= '25. 02. 2014 18:48:21';
convertSomeDate(someDate)
/* returned value: (Number)
1393354101000
*/