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
}
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'm trying to get the last of day of previous month using the current date:
var myDate = new Date();
According to MDN:
if 0 is provided for dayValue, the date will be set to the last day of the previous month.
But when set date to zero:
myDate.setDate(0)
console.log(JSON.stringify(myDate));
I get "2021-08-01T01:18:34.021Z" which first day of the current month. What is wrong with this approach?
JSON.stringify() is serializing the timestamp with a Z timezone, indicating UTC. The difference between UTC and your local timezone is causing the date to rollover to the next day.
You can use toLocaleString() to print the date in your local timezone:
var myDate = new Date();
myDate.setDate(0);
console.log(myDate.toLocaleString());
I would use dateInstance.toString() or dateInstance.toLocaleString():
const myDate = new Date;
myDate.setDate(0); myDate.setHours(0, 0, 0, 0);
console.log(myDate.toString()); console.log(myDate.toLocaleString());
You can use date-fns package
var df = require("date-fns")
let myDate = new Date() //Thu Aug 05 2021 22:16:09
let lastDayOfPrevMonth = df.endOfMonth(df.subMonths(myDate, 1)) //Sat Jul 31 2021 23:59:59 GMT-0400
I want to get the date from the GMT time but it returns the date which is one day ahead. How can I get the date mentioned in the GMT string always?
new Date("Mon, 27 Aug 2018 22:00:00 GMT").getDate()
This command returns 28 as the output, but I want 27.
Is there anything I need to add?
Thanks in advance.
Try this One.I think your problem will be solved.
<script>
function myFunction() {
var d = new Date();
var n = d.getUTCDate();
document.getElementById("demo").innerHTML = n;
}
</script>
When you create a new Date() the browser returns date based on your device timezone. You can use Date.getTimezoneOffset() to get GMT offset time difference and then adjust the time by multiplying the value.
// Your date
var myDate = new Date("Mon, 27 Aug 2018 22:00:00 GMT")
// Convert your date to local using getTimezoneOffset() and multiply with 60000 to get time adjusted GMT 0
var myDateLocal =new Date( myDate.valueOf() + myDate.getTimezoneOffset() * 60000 ).getDate();
document.getElementById("myDate").innerHTML=myDateLocal;
<h1 id="myDate" ></h1>
I need to increment hours to a date, but I can't get the correct date after change the hours. For example:
Change the current date
let x = new Date(); // 2018-05-30T00:17:04.888Z
x.setHours(x.getHours() + 24); // 2018-05-31T00:17:04.888Z
Great! Now the date should be 2018-05-31, right?
But if I try to do the following:
x.getDate();
It still returns old date: 2018-05-30 and the same happens for x.getHours()
Is there a way to handle that?
It seems to work just fine.
var date = new Date()
date
>Wed May 30 2018 03:26:19 GMT+0000 (UTC)
date.setHours( (date.getHours() + 23) )
>1527726379425
date
>Thu May 31 2018 00:26:19 GMT+0000 (UTC)
date.getDate()
>31
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.