I'm using AngularJS for my application and the date object is $scope.ProductionDate.
From 5:00AM 2017-02-21 (Feb 21st) to 4:59AM 2017-02-22 (Feb 22nd)
I want the ProductionDate value to be 2017-02-21.
P.S. Here Feb 21st is just an example. Daily I want the same value in given timings.
Can I know how to get that?
function Ctrl($scope)
{
$scope.ProductionDate = new Date();
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="Ctrl">
ProductionDate: {{ProductionDate | date:'yyyy-MM-dd'}}<br/>
</div>
You can subtract minutes and hours in javascript from the Date() object.
function Ctrl($scope)
{
var now = new Date();
now.setHours(now.getHours()-4);
now.setMinutes(now.getMinutes()-59);
$scope.ProductionDate = now;
}
It seems that you want to subtract 5 hours, so that the earlier date is shown.
Here is a SO post which explains how to modify Date object: Adding hours to Javascript Date object? (nevermind the title - you can use the same principles to subtract the hours).
This same operation may also be done by setting the desired timezone.
Just check if date hours are between 0 and 5 or not
function Ctrl($scope)
{
var now = new Date();
if(now.getHours() < 5 && now.getHours() >= 0){
// Subtract one day
now.setDate(now.getDate() - 1);
}
$scope.ProductionDate = now;
}
Related
I am trying to subtract hours from a given date time string using javascript.
My code is like:
var cbTime = new Date();
cbTime = selectedTime.setHours(-5.5);
Where selectedTime is the given time (time that i pass as parameter).
So suppose selectedTime is Tue Sep 16 19:15:16 UTC+0530 2014
Ans I get is : 1410875116995
I want answer in datetime format.
Am I doing something wrong here? Or there is some other solution?
The reason is that setHours(), setMinutes(), etc, take an Integer as a parameter. From the docs:
...
The setMinutes() method sets the minutes for a specified date
according to local time.
...
Parameters:
An integer between 0 and 59, representing the minutes.
So, you could do this:
var selectedTime = new Date(),
cbTime = new Date();
cbTime.setHours(selectedTime.getHours() - 5);
cbTime.setMinutes(selectedTime.getMinutes() - 30);
document.write('cbTime: ' + cbTime);
document.write('<br>');
document.write('selectedTime: ' + selectedTime);
Well first off setting the hours to -5.5 is nonsensical, the code will truncate to an integer (-5) and then take that as "five hours before midnight", which is 7PM yesterday.
Second, setHours (and other functions like it) modify the Date object (try console.log(cbTime)) and return the timestamp (number of milliseconds since the epoch).
You should not rely on the output format of the browser converting the Date object to a string for you, and should instead use get*() functions to format it yourself.
According to this:
http://www.w3schools.com/jsref/jsref_sethours.asp
You'll get "Milliseconds between the date object and midnight January 1 1970" as a return value of setHours.
Perhaps you're looking for this:
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_sethours3
Edit:
If you want to subtract 5.5 hours, first you have to subtract 5 hours, then 30 minutes. Optionally you can convert 5.5 hours to 330 minutes and subtract them like this:
var d = new Date();
d.setMinutes(d.getMinutes() - 330);
document.getElementById("demo").innerHTML = d;
Use:
var cbTime = new Date();
cbTime.setHours(cbTime.getHours() - 5.5)
cbTime.toLocaleString();
try this:
var cbTime = new Date();
cbTime.setHours(cbTime.getHours() - 5.5)
cbTime.toLocaleString();
This question already has an answer here:
new Date() for a specific timezone in JavaScript
(1 answer)
Closed 5 years ago.
This seemed fairly trivial but I might be over-thinking it.
I would like to render my chat widget between 9AM(PST) and 5PM(PST) mon-fri
Using new Date() always puts time into the browsers time zone. Basically i need to instantiate a date in PST and check if between days and hours.
var d = new Date();
var day = d.getDay();
var hour = d.getHours();
if (day > 0 && day < 6 && hour > 9 && hour < 17) {
renderChatWidget($('#chat-widget')):
}
I think this is incorrect because it uses the browser time, so if its 9:30AM in London then PST time would be like 2am and it would still render the chat widget...
function calcTime(city, offset) {
// create Date object for current location
var d = new Date();
// convert to msec
// subtract local time zone offset
// get UTC time in msec
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time for "+ city +" is "+ nd.toLocaleString();
}
document.getElementById('title').innerHTML=(calcTime('California', '-7'));
<h1 id="title">Time Zone Example</h1>
This is from this post and I just turned it into a snippet to see it work. You can then use the modified (correct) date through your tests using the correct time zone.
You can use UTC time.
var current_time = new Date;
var utc_time = Date.UTC(
current_time.getUTCFullYear(),
current_time.getUTCMonth(),
current_time.getUTCDate() ,
current_time.getUTCHours(),
current_time.getUTCMinutes(),
current_time.getUTCSeconds(),
current_time.getUTCMilliseconds());
I am quite low at javascript. I started to use moment.js library for my project to make javascript code to work by time & date, which always aligned by specific time zone. But I am struggling to understand how access different parts of my variable. My code:
var ItalyZone = "Europe/Rome";
var currentTime= moment().tz(ItalyZone).format();
alert(currentTime.hours()); //this is not working....
How can access only hours/minutes of that variable "currenTime" ?
How to set new hours for that variable "currentTime" ?
Using simple javascript Date() function I could do simply currentTime.getHours() / currentTime.setHours(), but how should I do using moment.js ???
Why use format when you just want the hours, return a date object instead
var ItalyZone = "Europe/Rome";
var currentTime = moment().tz(ItalyZone).toDate(); // return JS date object
var hours = currentTime.getHours()
You can use the get-set function to do this
moment().minute(Number);
moment().minute(); // Number
moment().minutes(Number);
moment().minutes(); // Number
Gets or sets the minutes.
You can use date format to get any part of date time:
var ItalyZone = "Europe/Rome";
moment().locale(ItalyZone).format("yyyy"); // year
moment().locale(ItalyZone).format("MM"); // month
moment().locale(ItalyZone).format("DD"); // day
moment().locale(ItalyZone).format("hh"); // hours
moment().locale(ItalyZone).format("mm"); // minutes
moment().locale(ItalyZone).format("ss"); // seconts
console.log(moment().locale(ItalyZone).format("YYYY MM DD hh mm ss"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
I have a javascript date variable as 04/05/2015, 01:30 (dd/mm/yyyy, HH:mm) format. Now how can I change that format to 04/05/2015, 01:00-01:30 format. Ie, I want to change the time with time range where the first time value is always 30 minutes less than second time value. So If the date is 04/05/2015, 13:00 then the formatted date would be 04/05/2015, 12:30-13:30
EDIT: See the fiddle here for the sample.
Please check the below solutions:
http://jsfiddle.net/ub942s6y/14/
You need to change data.addColumn('datetime', 'Date'); to 'string' as we are changing time
It will work fine. :)
Im affraid that there is no out-of-the-box functionality for what you are asking, and you will have to write your own function for that.
Here is a js Date object specification : Date Object
Your new function return type cannot be Date, as this kind of formatting can be only achieved with string type.
You can't have date object in that format. You will have manually create the format. It will be string.
var dateObj = new Date('04/05/2015, 01:30'), // input date
interval = 30, // interval in minutes
remainingInterval = 0;
var hours = dateObj.getHours(),
minutes = dateObj.getMinutes();
if(minutes > interval) {
minutes = minutes - interval;
} else {
remainingInterval = interval - minutes;
minutes = 60;
hours = hours - 1;
minutes = minutes - remainingInterval;
}
resulting date can be
console.log(dateObj.getDate()+'/'+dateObj.getMonth()+'/'+dateObj.getFullYear()+', '+dateObj.getHours()+':'+dateObj.getMinutes()+' - '+hours+':'+minutes);
I am trying to create a simple script that gives me the next recycling date based on a biweekly schedule starting on Wed Jul 6, 2011. So I've created this simple function...
function getNextDate(startDate) {
if (today <= startDate) {
return startDate;
}
// calculate the day since the start date.
var totalDays = Math.ceil((today.getTime()-startDate.getTime())/(one_day));
// check to see if this day falls on a recycle day
var bumpDays = totalDays%14; // mod 14 -- pickup up every 14 days...
// pickup is today
if (bumpDays == 0) {
return today;
}
// return the closest day which is in 14 days, less the # of days since the last
// pick up..
var ms = today.getTime() + ((14- bumpDays) * one_day);
return new Date(ms);
}
and can call it like...
var today=new Date();
var one_day=1000*60*60*24; // one day in milliseconds
var nextDate = getNextDate(new Date(2011,06,06));
so far so good... but when I project "today" to 10/27/2011, I get Tuesday 11/8/2011 as the next date instead of Wednesday 11/9/2011... In fact every day from now thru 10/26/2011 projects the correct pick-up... and every date from 10/27/2011 thru 2/28/2012 projects the Tuesday and not the Wednesday. And then every date from 2/29/2012 (leap year) thru 10/24/2012 (hmmm October again) projects the Wednesday correctly. What am I missing? Any help would be greatly appreciated..
V
The easiest way to do this is update the Date object using setDate. As the comments for this answer indicate this isn't officially part of the spec, but it is supported on all major browsers.
You should NEVER update a different Date object than the one you did the original getDate call on.
Sample implementation:
var incrementDate = function (date, amount) {
var tmpDate = new Date(date);
tmpDate.setDate(tmpDate.getDate() + amount)
return tmpDate;
};
If you're trying to increment a date, please use this function. It will accept both positive and negative values. It also guarantees that the used date objects isn't changed. This should prevent any error which can occur if you don't expect the update to change the value of the object.
Incorrect usage:
var startDate = new Date('2013-11-01T11:00:00');
var a = new Date();
a.setDate(startDate.getDate() + 14)
This will update the "date" value for startDate with 14 days based on the value of a. Because the value of a is not the same is the previously defined startDate it's possible to get a wrong value.
Expanding on Exellian's answer, if you want to calculate any period in the future (in my case, for the next pay date), you can do a simple loop:
var today = new Date();
var basePayDate = new Date(2012, 9, 23, 0, 0, 0, 0);
while (basePayDate < today) {
basePayDate.setDate(basePayDate.getDate()+14);
}
var nextPayDate = new Date(basePayDate.getTime());
basePayDate.setDate(nextPayDate.getDate()-14);
document.writeln("<p>Previous pay Date: " + basePayDate.toString());
document.writeln("<p>Current Date: " + today.toString());
document.writeln("<p>Next pay Date: " + nextPayDate.toString());
This won't hit odd problems, assuming the core date services work as expected. I have to admit, I didn't test it out to many years into the future...
Note: I had a similar issue; I wanted to create an array of dates on a weekly basis, ie., start date 10/23/2011 and go for 12 weeks. My code was more or less this:
var myDate = new Date(Date.parse(document.eventForm.startDate.value));
var toDate = new Date(myDate);
var week = 60 * 60 * 24 * 7 * 1000;
var milliseconds = toDate.getTime();
dateArray[0] = myDate.format('m/d/Y');
for (var count = 1; count < numberOccurrences; count++) {
milliseconds += week;
toDate.setTime(milliseconds);
dateArray[count] = toDate.format('m/d/Y');
}
Because I didn't specify the time and I live in the US, my default time was midnight, so when I crossed the daylight savings time border, I moved into the previous day. Yuck. I resolved it by setting my time of day to noon before I did my week calculation.