How to convert a string to a 24hr time? - javascript

So I have a JSON returning times like "10:00am"> i need to create an array with eight other times from the current system time. so it would go like "10:00am, 11:00am, 12:00pm, 1:00am, etc"
Here's my current code so far:
var katie=new Array();
var webdate = new Date().getHours();
var firsthr = day.date.start.time;
for (i=0; i<=8; i++){
katie{i] = webdate;
webdate = webdate +1;
}

You can try like this .
var str=new Array();
var webdate = new Date();
for (i=0; i<=8; i++){
webdate.setHours(i);
str[i] = webdate;
}

Date.js is a very helpful library for parsing strings into dates.
On this api doc page for Date.js search for ".parse". Also, the FormatSpecifiers page is helpful for converting dates to a string.
You said you have a JSON with the string, "10:00am". Assuming this JSON,
var data = {time: "10:00am"};
You could create a date object like this:
var date = Date.parse(data.time);
// this will create a date object with today's date and time set to 10am
Then, you can use your loop to increment the time to hours past 10am. Altogether it could look like this
<script src="date.js"></script>
<script>
var data = {time: "10:00am"};
var date = Date.parse(data.time);
//push today # 10am
var katie=new Array(new Date(date));
for (i=0; i<=8; i++){
//add an hour to date, then push new Date object based on date
date.add({hours:1});
katie.push(new Date(date));
}
</script>

You could try this -
var str=new Array();
var webdate = new Date();
var currenthours = webdate.getHours();
var looplimit = currenthours + 8;
for (i=currenthours; i<looplimit; i++){
webdate.setHours(i);
str[i] = webdate.getHours() >= 12 ? webdate.getHours() -12 +':00pm' : webdate.getHours() +':00am';
}
}

Related

Javascript - Adding Days to a Loop

I have the following
var my_date = '2021-09-27';
my_date = new Date(my_date);
var new_date = new Date();
for(var i=0; i<10; i++)
{
new_date.setDate(my_date.getDate() + i);
var this_date = new_date.toISOString();
console.log(this_date);
}
I was expecting it to output
2021-09-27T19:21:26.361Z
2021-09-28T19:21:26.361Z
2021-09-29T19:21:26.361Z
2021-09-30T19:21:26.361Z
2021-10-01T19:21:26.361Z
2021-10-02T19:21:26.361Z
2021-10-03T19:21:26.361Z
2021-10-04T19:21:26.361Z
2021-10-05T19:21:26.361Z
2021-10-06T19:21:26.361Z
but for some reason it outputs
2021-10-27T19:21:26.361Z
2021-10-28T19:21:26.361Z
2021-10-29T19:21:26.361Z
2021-10-30T19:21:26.361Z
2021-10-31T19:21:26.361Z
2021-11-01T19:21:26.361Z
2021-12-03T19:21:26.361Z
2022-01-03T19:21:26.361Z
2022-02-04T19:21:26.361Z
2022-03-08T19:21:26.361Z
As you can see it starts in October not September, and then when it hits the 31st it starts to jump months.
Why is this script behaving like this?
All the examples I have found online seem to suggest this would work.
Thanks
Because setDate only changes days, so when you create new Date() it has current month in it. You have to copy original date to make this works properly.
Here's the fix:
var my_date = '2021-09-27';
my_date = new Date(my_date);
for(var i=0; i<10; i++)
{
// clone date
var new_date = new Date(my_date.getTime())
new_date.setDate(my_date.getDate() + i);
var this_date = new_date.toISOString();
console.log(this_date);
}

Store every year directly from the date of entry of a user

Hi I need to store every year directly from the date of entry of a user to the business the problem is that every time I add a year is inserted between the day and month.
var yearOnCompany = moment(user.fecha_ingreso_empresa, "YYYYMMDD").fromNow();
var dateStart = moment(user.fecha_ingreso_empresa).format("DD-MM-YYYY");
console.log(dateStart);
//03-12-2009
var f = parseInt(yearOnCompany);
var yearsOfWork = [];
for(var i = 1; i <= f; i++)
{
dateStart = moment(dateStart, "DD-MM-YYYY").add(1, 'years').calendar();
yearsOfWork.push(dateStart);
}
console.log(yearsOfWork);
Result of this:
0:"12/03/2010"
1:"03/12/2011"
2:"12/03/2012"
3:"03/12/2013"
4:"12/03/2014"
5:"03/12/2015"
6:"12/03/2016"
7:"03/12/2017"
This is a subtle error! According to the moment docs https://momentjs.com/docs/#/displaying/ .calendar() uses a default date format, possibly using the locale of the environment, if none is provided, so here it looks like it's defaulting to MM/DD/YYYY, rather than the desired DD/MM/YYYY. So on the first iteration dateStart is converted to 12/03/2010 with the month and day swapped. Then on the next iteration it's converted back to DD-MM-YYYY, again with the day and month swapped, then when passed to .calendar() again the day and month swap again giving the correct format again.
A potential bug is that you're changing dateStart from a string to a moment object, so I'd rewrite the code like this:
var dateStart = moment(user.fecha_ingreso_empresa).format("DD-MM-YYYY");
var f = parseInt(yearOnCompany);
var yearsOfWork = [];
for(var i = 1; i <= f; i++)
{
dateStart.add(1, 'years');
yearsOfWork.push(dateStart.format("DD-MM-YYYY"));
}
console.log(yearsOfWork);
I think you have the problem with the format, correct me if I am wrong.
Please try this.
for(var i = 1; i <= f; i++)
{
dateStart = moment(dateStart , "DD-MM-YYYY").add(1, 'years');
yearsOfWork.push(dateStart.format('DD-MM-YYYY'));
}

get an array of dates for the past week in format dd_mm

I need to have an array of dates for whole days of the last week, including the current day, for e.g
['05/06', '04/06', '03/06', '02/06', '01/06', '31/05', '30/05']
(format dd/mm)
how can i do this?
I know there is the Date() object, but other than that I'm stumped.
logic along the lines of:
var dates = [];
var today = new Date();
for (var i = 0; i<7; i++){
var date = today - (i+1);
dates.push(date);
}
So you want an array containing todays date and a further 6 elements, with todays date-1, todays date-2 etc...?
var dates = [];
var date = new Date();
for (var i = 0; i < 7; i++){
var tempDate = new Date();
tempDate.setDate(date.getDate()-i);
var str = tempDate.getDate() + "/" + tempDate.getMonth();
dates.push(str);
}
console.log(dates);
Output: ["5/5", "4/5", "3/5", "2/5", "1/5", "31/4", "30/4"]
If you need numbers with leading 0's, try this:
var dates = [];
var date = new Date();
for (var i = 0; i < 7; i++){
var tempDate = new Date();
tempDate.setDate(date.getDate()-i);
var str = pad(tempDate.getDate()) + "/" + pad(tempDate.getMonth());
dates.push(str);
}
console.log(dates);
function pad(n) {
return (n < 10) ? ("0" + n) : n;
}
Output: ["05/05", "04/05", "03/05", "02/05", "01/05", "31/04", "30/04"]
Check this working sample, where all days are printed out:
http://jsfiddle.net/danyu/Tu5R6/6/
This is the main logic:
for(var i=7;i>0;i--)
{
tempDate.setDate(tempDate.getDate()-1);
output+=tempDate+"<br/>";
}
Modify it to store those days into your array.

Dates between two dates

I have for example two dates:
var first = '2013-07-30';
var second = '2013-08-04';
How can i show all dates between first and second?
This should return me:
2013-07-30
2013-07-31
2013-08-01
2013-08-02
2013-08-03
2013-08-04
In PHP I can get dates to strtotime and use a while loop. But how can I do it in jQuery?
I would like have this in array.
var day = 1000*60*60*24;
date1 = new Date('2013-07-30');
date2 = new Date("2013-08-04");
var diff = (date2.getTime()- date1.getTime())/day;
for(var i=0;i<=diff; i++)
{
var xx = date1.getTime()+day*i;
var yy = new Date(xx);
console.log(yy.getFullYear()+"-"+(yy.getMonth()+1)+"-"+yy.getDate());
}

How to check if any date from array is in date range?

Hope you are all well.
I need to check if any date from array
var arrayDates = ["2013-07-26", "2013-07-27"];
is in date range of
var startDate = new Date("2013-07-10");
var endDate = new Date("2013-07-10");
I am really stuck and started to confuse myself. Can anyone help me with that please.
P.S. Dates above are for example, they will be dynamic.
Thank you!
You will need to use real date objects rather than strings.
maybe have a look at using dateJs for parsing dates
http://www.datejs.com/
But really you need to iterate through the array of dates and check if they fall between the tick value of your start and end dates.
Try this:
var arrayDates = [];
arrayDates.push(new Date(2013, 7 , 26));
arrayDates.push(new Date(2013, 7 , 27));
var startDate = new Date("2013-07-10");
var endDate = new Date("2013-07-10");
for(i = 0; i < arrayDates.length; i++){
if(arrayDates[i] >= startDate && arrayDates[i] <= endDate) {
alert('Yes');
}
}
Another method - http://jsfiddle.net/Mh5vn/
var ds = ["2013-07-26", "2013-07-27"];
Array.prototype.between = function(arg) {
var d1 = new Date(this[0]),
d2 = new Date(this[1]),
d3 = new Date(arg);
return (d1.getTime() <= d3.getTime() && d3.getTime() <= d2.getTime());
}
console.log( ds.between('2013-07-26') );
// true
console.log( ds.between('2013-07-28') );
// false
After you have the date objects you can compare them in a pretty straight forward way. See this link at the bottom.
I see your question is tagged jquery, so you could do something like this:
$.each(arrayDates, function(i, val) {
if (val > endDate || val < startDate)
{
//Date is outside of that range
}
});
Hopefully you can convert these dates to numbers and compare them, here an example :
var arrayDates = ["2013-07-26", "2013-07-27"];
var unDash = function (string) {
return string.replace(/-/g, "")
}
var dateInRange = function (date, startDate, endDate) {
date = unDash(date)
startDate = unDash(startDate)
endDate = unDash(endDate)
return date > startDate && date < endDate
}
// You now filter your array to retrieve your dates
var dates = arrayDates.filter(function (date) {
return dateInRange(date, '2013-07-10', '2013-07-31')
})

Categories