I have a simple code that echos the current Hour+Minute+Date as one number sequence.
I need to add 1 to all the numbers outputted, individually.
Example: If the current time and date is: 22321512 then i need jQuery to output: 33432623.
My knowledge in jQuery is pretty slim, How can this be achieved?
HTML:
<span id="date"></span>
Code:
var now = dateFormat(new Date(), "HHMMddmm");
$('#date').append(now);
You need to do the following roughly:
var currentDate = new Date();
var myDate = new Date(currentDate.getYear() + 1, currentDate.getMonth() + 1, currentDate.getDay() + 1);
alert(myDate.getTime());
Should solve your problem.
If you want to merely increment each unit by 1 and let the JavaScript engine advance the date and time on overflow, then Captain John's answer will work perfectly.
This means that, for example, if this routine were to be run at 11:59 PM on December 31, your output would be 00000100.
If you want each unit to be incremented by 1 without the date being advanced, you will have to stop relying on Steven Levithan's [excellent] dateFormat library and do it yourself:
var now = new Date(),
hours = now.getHours() + 1, // add 1 hour
minutes = now.getMinutes() + 1, // add 1 minute
date = now.getDate() + 1, // add 1 day
month = now.getMonth() + 1, // add 1 month
padLeft = function (val) { // make a formatter
while (val.length < 2) {
val = '0' + val; // string is less than 2 characters, pad left side with '0'
}
return val; // return formatted string
},
formatted = padLeft(hours) + padLeft(minutes) + padLeft(date) + padLeft(month);
$('#date').append(formatted);
Getting number length as string you can easily sum 1 to each number.
The result is given as timestamp
To get Date object, use new Date(result);
var now = new Date().getTime(); // 22321512 on your example
// Answer
var result = 0;
var str = now.toString();
for(var i = 0; i < str.length; i++) {
result += Math.pow(10, i);
}
result += now; // Ex.: 22321512 + 11111111
Related
I've tried to get the mother day date (first sunday of may) by Javascript. But the result of my code is 0.4.2021. Where is the fault or there a much more simplier way to get the mothers day date (dd.mm.yyyy) (german time zone).
var currentYear = new Date().getFullYear()
var mayFirst = new Date(currentYear + '-05-01');
var dayOfWeek = mayFirst.getUTCDay();
var firstSunday;
if (dayOfWeek === 0) {
firstSunday = mayFirst;
} else {
firstSunday = new Date();
firstSunday.setDate(1 + (7 - dayOfWeek));
}
var mothersDay = new Date(firstSunday);
mothersDay.setDate(firstSunday.getUTCDate() + 7);
mothersDay = new Date(mothersDay);
console.log(mothersDay.getDay() + "." + mothersDay.getMonth() + "." + mothersDay.getFullYear());
Here's the proper way of doing this, without error-prone calculations or string concatenation, including formatting it as DD.MM.YYYY:
// Mother's Day is the second sunday in May
const d = new Date();
d.setMonth(4); // May
d.setDate(8); // May 8 is the earliest possible date
// while not a sunday, move to next day
while (d.getUTCDay()) d.setDate(d.getDate() + 1);
const result = new Intl.DateTimeFormat('de-DE', { day: "2-digit", month: "2-digit", year: "numeric"}).format(d);
document.body.innerHTML += result;
getMonth() is 0 based so you need to add 1 to that. Also you want to use getDate() instead of getDay() to get the day value of the date.
I assume you want to get the 2nd sunday of may since the line below from your code adds 7 days. If you want the first sunday you should remove this line too.
mothersDay.setDate(firstSunday.getUTCDate() + 7);
var currentYear = new Date().getFullYear()
var mayFirst = new Date(currentYear + '-05-01');
var dayOfWeek = mayFirst.getUTCDay();
var firstSunday;
if (dayOfWeek === 0) {
firstSunday = mayFirst;
} else {
firstSunday = new Date();
firstSunday.setDate(1 + (7 - dayOfWeek));
}
var mothersDay = new Date(firstSunday);
mothersDay.setDate(firstSunday.getUTCDate() + 7);
mothersDay = new Date(mothersDay);
console.log(mothersDay.getDate() + "." + (mothersDay.getMonth() + 1) + "." + mothersDay.getFullYear());
Environment: Win 10 Pro, Chrome 85, luxon 1.25.0
What I am trying to achieve eventually is this: in an ASP.Net/c# application show to the user continuously the amount of time until a session time out will occur. Because server and client may be in different time zones I need the UTC offset of each. The client's offset is easy to get. To find the server's offset (with reference to the code snippet below): the server code puts the page last loaded time into lblLastLoaded. Object dto receives the parsed date parts, including dto.offset which, I gather, is supposed to be expressed in minutes. The subsequent call to luxon.DateTime.fromObject(dto) fails: pst is left undefined. When I do not set dto.offset (by commenting out 4 lines in the code below) pst gets the server time successfully, but without the offset; it appears that luxon uses the offset of my local system which is -7 hours.
<script>
function r4onload() {
// Get server time:
var st = document.getElementById('lblLastLoaded').innerHTML;
// Date Time Offset
// st has form YYYY/MM/dd HH:mm:ss -HH:mm
// 1 2
// 012345678901234567890123456
// For Example 2020/09/29 10:31:56 -07:00
let dto = {};
dto.year = Number(st.substring(0, 4));
dto.month = Number(st.substring(5, 7));
dto.day = Number(st.substring(8, 10));
dto.hour = Number(st.substring(11, 13));
dto.minute = Number(st.substring(14, 16));
var offsetHour = Number(st.substring(20, 23)); // works if these 4 lines are commented out
var offsetMinutes = Number(st.substring(24, 26)); // works if these 4 lines are commented out
dto.offset = offsetHour * 60 + Math.sign(offsetHour) * offsetMinutes; // works if these 4 lines are commented out
// dto.offset is correctly calculated to -420 minutes // works if these 4 lines are commented out
var pst = luxon.DateTime.fromObject(dto);
// pst is undefined at this point -- why??
// If I do not include anything about offset above (comment out the 4 lines
// containing offsetHours, offsetMinutes, and dto.Offset, then pst comes out like this:
// 2020-09-29T10:31:00.00000-07:00
// i.e., luxon used the offset -07:00 of my local system, not the one contained in variable st.
document.getElementById('Parsed').innerHTML = pst;
r4startTime();
}
function r4startTime() {
var dt = luxon.DateTime.local();
var h = dt.hour;
var m = dt.minute;
var s = dt.second;
m = r4checkTime(m);
s = r4checkTime(s);
document.getElementById('CurrTime').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(r4startTime, 2000);
}
function r4checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
A complete Visual Studio 2017 project DemoLuxon with the above code snippet in file Site.Master is here: https://1drv.ms/u/s!AvoFL8QrGVaTsQvbaB8-Zh7GdloV?e=ODjZW5
If the above approach is awkward, I would be grateful for suggestions of more elegant ways of determining the client/server offset difference.
I devised a workaround as follows below, but the original problem has not been answered:
<script>
function r4onload() {
var st = document.getElementById('lblLastLoaded').innerHTML;
// Date Time Offset
// st has form YYYY/MM/dd HH:mm:ss -HH:mm
// 1 2
// 012345678901234567890123456
// For Example 2020/09/29 10:31:56 -07:00
// Transform to ISO format:
st = st.substring(0, 4) + '-' + st.substring(5, 7) + '-' + st.substring(8, 10)
+ 'T' + st.substring(11, 19) + ".000" + st.substring(20);
document.getElementById('Xformed').innerHTML = st;
var pst = luxon.DateTime.fromISO(st, { setZone: true });
document.getElementById('Parsed').innerHTML = pst;
r4startTime();
}
function r4startTime() {
var dt = luxon.DateTime.local();
var h = dt.hour;
var m = dt.minute;
var s = dt.second;
m = r4checkTime(m);
s = r4checkTime(s);
document.getElementById('CurrTime').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(r4startTime, 2000);
}
function r4checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
i.e., put the date-time first into ISO format and then use luxon.DateTime.fromISO. Variable pst gets the correct date-time value including the offset. The problem with luxon.DateTime.fromObject with an offset remains unresolved.
I'm trying to produce a graph like the following:
From an array of events as follows:
var events = {
"0": {"guid": "78926349827546", "created": "2017-07-07 14:14:21" },
"1": {"guid": "78926349827546", "created": "2017-07-08 15:44:10" },
"2": {"guid": "20936752065745", "created": "2017-07-09 12:09:24" },
"3": {"guid": "20936752065745", "created": "2017-07-11 06:55:42" },
"4": {"guid": "20936752065745", "created": "2017-07-11 22:10:29" },
...
};
I'm currently using the Google Line Chart. Although I'm happy with the aesthetic, I still need to find a way to produce a tabbed display of several timescales, e.g. Today, Last 7 Days, Last Month and Total.
Programmatically, this is proving to be a sisyphean task, as I have to count occurrences across (in one instance) every hour in the last day, and then (in another instance) every day in the last week etc.
And there's a lot of date conversion, counting backwards from today and so on.
Is there a way of taking my array and producing a new array of human-readable dates relative from today, across several timescales?
This is really a duplicate of a couple of questions like Where can I find documentation on formatting a date in JavaScript?, How to add months to a date in JavaScript? and Add days to JavaScript Date. So there are plenty of existing examples to work from.
Also, Google Charts has its own date formatter.
Anyway, you might use a function that takes a start date, end date and increment and returns an array of timestamps in a particular format. Formatting the strings can use a second function or the Google Charts formatter.
A bare bones version is very little code, to add some logic for forward or backward series takes a few more lines.
// Return date string in YYYY-MM-DD HH:mm:ss format
function formatDate(date) {
function z(n){return (n<10? '0':'') + n}
return date.getFullYear() + '-' +
z(date.getMonth() + 1) + '-' +
z(date.getDate()) + ' ' +
z(date.getHours()) + ':' +
z(date.getMinutes()) + ':' +
z(date.getSeconds());
}
// Return date strings from start date to end date
// with increment inc in hours
function getDateSeries(start, end, inc) {
var d = new Date(+start);
inc = +inc;
var dates = [];
// Deal with backwards sequences
var reverse = false, t;
if (start > end) {
t = start;
start = end;
end = t;
reverse = true;
}
if (inc < 0) {
reverse = true;
inc *= -1;
}
while (start <= end) {
dates.push(formatDate(start));
start.setHours(start.getHours() + inc);
}
return reverse? dates.reverse() : dates;
}
// Hourly intervals over 2 days forwards
console.log(getDateSeries(new Date(2017,7,18), new Date(2017,7,19), 1));
// 6 hourly intervals over 10 days backwards
console.log(getDateSeries(new Date(2017,7,28), new Date(2017,7,18), -6));
// Hourly intervals from now going back 24 hours
var now = new Date();
var end = new Date(+now);
end.setDate(end.getDate() - 1);
console.log(getDateSeries(now, end, -1))
// Daily intervals from today going back 30 days
var now = new Date();
now.setHours(0,0,0,0);
var end = new Date(+now);
end.setDate(end.getDate() - 30);
console.log(getDateSeries(now, end, -24))
There are plenty of libraries around to help with formatting, incrementing and decrementing dates but if this is all you want to do, it doesn't take much to write.
This could be modified so the start is always "now" or "today" and use an interval in days rather than a start and end date with hours.
Where a library would come in handy is if you want say monthly intervals on the last day of the month or similar (since months aren't of equal length). So using moment.js you could do:
function getMonthlySequenceStart(months) {
var format = 'YYYY-MM-DD HH:mm:ss'
var now = moment().startOf('month');
var count = Math.abs(months);
var direction = months < 0? -1 : 1;
var result = [];
while (count--) {
result.push(now.format(format));
now.add(direction, 'months');
}
return result;
}
console.log(getMonthlySequenceStart(-12));
function getMonthlySequenceEnd(months) {
var format = 'YYYY-MM-DD HH:mm:ss'
var now = moment().endOf('month').startOf('day');
var count = Math.abs(months);
var direction = months < 0? -1 : 1;
var result = [];
while (count--) {
result.push(now.format(format));
now.add(direction, 'months');
now.endOf('month').startOf('day');
}
return result;
}
console.log(getMonthlySequenceEnd(-12));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Not using a library isn't too hard either. The following sets the date to the first of the month as then it's easy to decrement by 1 month, then get the day before (the last day of the previous month) for the string:
// Sequence of end of months from current month
// back for num months
function getMonthlySequenceEnd(num) {
var now = new Date();
now.setHours(0,0,0,0);
var t, result = [];
// Set to first day of next month
now.setMonth(now.getMonth() + 1, 1)
while (num--) {
t = new Date(+now);
t.setDate(t.getDate() - 1);
result.push(formatDate(t));
now.setMonth(now.getMonth() - 1);
}
return result;
}
function formatDate(date) {
function z(n) {return (n < 10 ? '0' : '') + n}
return date.getFullYear() + '-' + z(date.getMonth() + 1) + '-' + z(date.getDate()) + ' ' +
z(date.getHours()) + ':' + z(date.getMinutes()) + ':' + z(date.getSeconds());
}
console.log(getMonthlySequenceEnd(24));
So I think you now have enough to do whatever is required.
I have two date with time:
YY:MM:DD hh:mm
This is the time period
I need to calculate gap and divide it into 'n' equal parts.
In order to build a graph
Pls Help
Because date is actually saved as an integer and only shown as
YY:MM:DD hh:mm
You can actually just take the two date variables and devide them by the n
gap = (date1 - date2)/n
and then you can get the intervals by just adding the gap multiple times
for(var i = 1; i <= n; i++){
newDate[i] = new Date(date2 + gap*i);
}
something like this?
you can operate directly with dates in javascript
var date1 = new Date(2017, 01, 01, 10, 15, 00);
var date2 = new Date(2016, 12, 01, 10, 14, 45);
var dateDiff = new Date(date1-date2); //this will return timestamp
var years = dateDiff.getFullYear() - 1970; //init date always is 1970
var months = dateDiff.getMonth();
var days = dateDiff.getDate();
var minutes = dateDiff.getMinutes();
var seconds = dateDiff.getSeconds();
alert(years + " years.\r " +
months + " months\r" +
days + " days\r" +
minutes + " minutes\r" +
seconds + " seconds");
I would suggest that you try out the momentjs library. It provides powerful functionalities for you to conveniently work with date objects.
For example, given 2 string dates that are properly formatted, you can get the precise difference between the 2 times easily like so:
let time1 = moment("04/09/2013 15:00:00");
let time2 = moment("04/19/2013 18:20:30");
let diffMilliseconds = time1.diff(time2); // gives the time difference in milliseconds
let diffDays = time1.diff(time2, 'days'); // gives the time difference in days
You can use the date object to convert the given time format to timestamp and then find difference between timestamp.
For example:
var date1 = "2017-03-04 11:22:22"
var date2 = "2017-03-04 13:11:42"
var timestamp1 = Date.parse(date1, "YYYY-MM-DD HH:mm:ss")
var timestamp2 = Date.parse(date2, "YYYY-MM-DD HH:mm:ss")
var difference = timestamp2 - timestamp1;
console.log(difference) //in milliseconds
Now you can divide the difference in to n parts and add to timestamp1 to get following timestamp based on difference/n interval.
Forgive me I tried several searches here and other places in general but cant seem to fix issue I am having at the moment. Can someone please help me figure out?
I am trying to find quarter strings from inputdate in JavaScript. For "01/31/2009" it should give Q1,2013 Q4,2012 etc based on offset given as input parameter. when offset is 0 then current quarter, 1 then previous, 2 then previous 2 quarter etc...
my current code: jsfiddle
function getQuarterStrings(id) {
var d = new Date();
var d = new Date("01/31/2009");
var str;
switch (id) {
...
}
Remaining code is in jsfiddle. As you can see, it fails on second last condition even though everything seems ok. Please help me figure out my mistake. Thank you!
Some of your comparisons are off, and Date tries to compensate for months that don't have as many days when you setMonth. This code should work:
function getQuarterStrings(id) {
var d = new Date("03/31/2009");
d.setDate(1);
d.setMonth(d.getMonth() - id * 3);
var month = d.getMonth() + 1;
var year = d.getFullYear();
var quarter = Math.ceil(month / 3);
return ("Q" + quarter + ", " + year);
}
This works, and is a lot more concise. It also allows you to use any offset instead of a limited set of values:
function getQuarterStrings(date, id) {
// quarter is 0-based here
var quarter = Math.floor(date.getMonth() / 3),
year = date.getFullYear();
quarter -= id;
if(quarter < 0) {
var yearsChanged = Math.ceil(-quarter / 4);
year -= yearsChanged;
// Shift quarter back to a nonnegative number
quarter += 4 * yearsChanged;
}
return "Q" + (quarter + 1) + ", " + year;
}
http://jsfiddle.net/dPmf2/6/
You can also get rid of the switch statement by doing this:
function getQuarterStrings(id) {
var d = new Date();
var d = new Date("01/31/2009");
var str;
if (id !== 0){
d.setMonth(d.getMonth() - 3*id);
}
str = getQuarter(d);
return str;
}