i want to change Local time to UTC and vice-versa, by taking users date value.(User will choose the dateand Time and according to dates it will change to UTC and vice versa )
Can someone help on this
If you have your date+time in a JavaScript Date object you can call its getUTCDate()method to get a new Date whose time zone is UTC.
If that is not what you have in mind please be more specific about what you mean by “it will change”.
You can try this:
function calculateTimestamp(date) {
date = date.split('-');
var year = date[2];
var month = date[1];
var day = date[0];
var d1 = new Date(Date.UTC(2017, 9, 1, 17, 0, 0, 0)); //It is static time based upon you will count time in ms
var d2 = new Date(Date.UTC(year, (month - 1), day, 17, 0, 0, 0));
return parseInt((d2.getTime() - d1.getTime()) / 1000);
}
var startDate = '27-02-2018';
var startTime = calculateTimestamp(startDate);
Now you can convert this timestamp again as below:
var d = new Date(Date.UTC(2017, 9, 1, 17, 0, 0, 0));
var t = parseInt(d.getTime() / 1000);
var d = new Date((startTime + t) * 1000);
Related
As the title says I want to calculate the number of weeks between a start date and end date I'm a bit confuse can someone shed some light on me.
var start_date = new Date();
var end_date = new Date(2018,09,30);
use moment.js.
var start_date = new Date();
var end_date = new Date(2018,09,30);
change to format
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now, "DD/MM/YYYY HH:mm:ss").diff(moment(then, "DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
you can get total no of days, you can divide/7. so that you can get no of weeks.
function diff_weeks(dt2, dt1)
{
var diff =(dt2.getTime() - dt1.getTime()) / 1000;
diff /= (60 * 60 * 24 * 7);
return Math.abs(Math.round(diff));
}
dt1 = new Date(2018,09,25);
dt2 = new Date(2018,10,02);
alert(diff_weeks(dt1, dt2));
dt1 = new Date("September 25, 2018 08:11:00");
dt2 = new Date("October 02, 2018 08:11:00");
alert(diff_weeks(dt1, dt2));
this function will give you the difference in weeks
Try this code and number of weeks will be shown in dateArr also you will see here every week start- end. You can edit code for your needs.
var start = new Date(Date.UTC(2016, 09, 30, 0, 0, 0));
var end = new Date(Date.UTC(2016, 11, 02, 0, 0, 0));
var sDate;
var eDate;
var dateArr = [];
while(start <= end){
if (start.getDay() == 1 || (dateArr.length == 0 && !sDate)){
sDate = new Date(start.getTime());
}
if ((sDate && start.getDay() == 0) || start.getTime() == end.getTime()){
eDate = new Date(start.getTime());
}
if(sDate && eDate){
dateArr.push({'startDate': sDate, 'endDate': eDate});
sDate = undefined;
eDate = undefined;
}
start.setDate(start.getDate() + 1);
}
console.log(dateArr);
There are some really cool JavaScript libraries you can use for this. A nice lightweight one would be date-fns. I’ve linked the download link and I’ve written some example code for you from their documentation:
Download it/add it to your packages: https://date-fns.org
Documentation: https://date-fns.org/v1.29.0/docs/differenceInWeeks
Example:
// How many full weeks are between 5 July
// 2014 and 20 July 2014?
var result = differenceInWeeks(
new Date(2014, 6, 20),
new Date(2014, 6, 5)
)
//=> 2
i have this time format :
DateTime(2015, 5, 11, 12, 0, 0)
i would like to know if i can convert it into a time stamp.
i have made this convert function from ISO 8601 to Timestamp and i would like to know if i can adapt it to this time format :
var myDate = new Date("2017-07-31T15:30:00+0000");
var offset = myDate.getTimezoneOffset() * 60 * 1000;
var withOffset = myDate.getTime();
var withoutOffset = withOffset - offset;
console.log(myDate.getTimezoneOffset()*60 * 1000)
console.log('with Offset ' + withOffset);
console.log('without Offset (timeStamp of your timezone) ' +withoutOffset);
did you try
Date.parse(your date here)/1000
Date.parse(new Date(2015, 5, 11, 12, 0, 0))/1000
you can use the library momentjs to convert it.
Here you are assigning an instance of momentjs to CurrentDate:
var CurrentDate = moment();
Here just a string, the result from default formatting of a momentjs instance:
var CurrentDate = moment().format();
And here the number of seconds since january of... well, unix timestamp:
var CurrentDate = moment().unix();
momentjs guide
Parsing dates is a pain in JavaScript as there's no extensive native support. However you could do something like the following by relying on the Date(year, month, day [, hour, minute, second, millisecond]) constructor signature of the Date object.
var dateString = '17-09-2013 10:08',
dateTimeParts = dateString.split(' '),
timeParts = dateTimeParts[1].split(':'),
dateParts = dateTimeParts[0].split('-'),
date;
date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);
console.log(date.getTime()); //1379426880000
console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400
I've been working with DateRangeSlider for a couple of days and now I'm using it as a time slider - fiddle
My problem is that the min time is 02:00 and it needs to be 00:00, and max time is 01:59 instead of 23:59.
If I changed the formatter values from
h = val.getHours(),
m = val.getMinutes();
to
h = val.getUTCHours(),
m = val.getUTCMinutes();
it displays the correct start-end hour but when I'm getting those values:
var values = $("#slider").dateRangeSlider('values');
var test = values.min;
it still gets the other values: 02:00 instead of 00:00.
Is there any way to format the min/max value but when the values are read to display the same hour?
You need to take into account the TimeZone and also the Daylight Saving Time (the Date() object is relied on them).
Your solution can be:
var minDateStr = "2014-01-01T00:00:00Z";
var maxDateStr = "2014-01-01T23:59:00Z";
var min2 = new Date(new Date(minDateStr).getTime() + new Date(minDateStr).getTimezoneOffset() * 60000),
max2 = new Date(new Date(maxDateStr).getTime() + new Date(maxDateStr).getTimezoneOffset() * 60000);
Here is a fix to your jsfiddle:
http://jsfiddle.net/z1govrt7/
I have updated format for date and time as below
var min2 = new Date(2014, 0, 1, 00, 00, 00),
max2 = new Date(2014, 11, 31, 23, 59, 59);
Please check http://jsfiddle.net/LJrYf/149/ fiddle now.
I have updated your code and now its working as expected.
Is there a way to intelligently find the beginning and end times of a specific Date object in JavaScript for a certain time window (month, day, year, week)?
I'd like to be able to give it any date, then an identifier (like month, week, day, or year), then a boolean for whether or not it should use UTC time. It should return a JavaScript object with two keys (startTime, endTime) where the values for these keys are the epoch milliseconds (or date objects) representing my range.
I began writing a function to do this (see below), just wondering if there is a smarter way to go about doing it:
/**
* #param rangeValue; String ('year', 'month', 'week', 'day')
* #param dateTime; JavaScript Date Object.
* #param useUTC; Boolean. Determines whether or not UTC is to be used or default browser time
* #returns {{}}; startTime and endTime, in epoch milliseconds
*/
function generateTimeRange(rangeValue, dateTime, useUTC) {
var dateRange = {};
var year = dateTime.getUTCFullYear();
var month = dateTime.getUTCMonth();
var dayOfWeek = dateTime.getUTCDay();
var day = dateTime.getUTCDate();
if (!useUTC) {
year = dateTime.getFullYear();
month = dateTime.getMonth();
dayOfWeek = dateTime.getDay();
day = dateTime.getDate();
}
if (rangeValue === 'year') {
dateRange.startTime = new Date(year, 0, 0, 0, 0, 0, 0).getTime();
dateRange.endTime = new Date(year + 1, 0, 0, 0, 0, 0, 0).getTime() - 1;
} else if (rangeValue === 'month') {
dateRange.startTime = new Date(year, month, 0, 0, 0, 0, 0).getTime();
month += 1;
if (month > 11)
year += 1;
dateRange.endTime = new Date(year + 1, month % 12, 0, 0, 0, 0, 0).getTime() - 1;
} else if (rangeValue === 'week') {
// Do week calculation
} else if (rangeValue === 'day' {
// Do day calculation
}
return dateRange;
}
EDIT: Just discovered that Moment.js has startOf and endOf methods. Is there an elegant way to do this without external libraries?
This is probably more suitable in a code review forum.
It doesn't seem sensible to get all the UTC parts, then see if you need them and get local parts if not. Just get the ones you want. And since UTC should be used everywhere if required, then:
var UTC = useUTC? 'UTC' : '';
Now you just do:
var year = dateTime.['get' + UTC + 'FullYear']();
var month = dateTime.['get' + UTC + 'Month']();
and so on. But there's no need to do those unless you must. Then there's:
if (rangeValue === 'year') {
that is pretty strict, you might want it case–insensitive so:
if (/^year$/i.test(rangeValue))
then
dateRange.startTime = new Date(year, 0, 0, 0, 0, 0, 0).getTime();
will get 31 December of the previous year since you've set the date to 0. It will also be 00:00:00 for the host system timezone, not UTC (if it was specified). If you only provide the year and month, all the other values are zero (except for date, it's 1) by default, and you want to use UTC if specified so:
dateRange.startTime = (UTC? new Date(Date.UTC(year,0)) : new Date(year,0)).getTime();
Similarly for end time:
dateRange.endTime = (UTC? new Date(Date.UTC(+year+1,0)) : new Date(+year+1,0)).getTime() - 1;
You actually don't need getTime since the subtraction will coerce the value to a number anyway, but it keeps things consistent. To do month is similar:
// Get the month
var month = dateTime['get' + UTC + 'Month']();
// If month range is required
if (/^month$/i.test(rangeValue)) {
// Get the start of the month
var monthStart = UTC? new Date(Date.UTC(year,month)) : new Date(year,month);
// Assign the time value
dateRange.startTime = monthStart.getTime();
// Adjust to end of month.
// The setTime method returns the time value, so no need for getTime
dateRange.endTime = monthStart['set' + UTC + 'Month'](monthStart['get' + UTC + 'Month']() + 1, 1) - 1;
return dateRange;
}
So putting that part together:
function generateTimeRange(rangeValue, dateTime, useUTC) {
var dateRange = {};
var UTC = useUTC? 'UTC' : '';
var year = dateTime['get' + UTC + 'FullYear']();
if (/^year$/i.test(rangeValue)) {
dateRange.startTime = (UTC? new Date(Date.UTC(year,0)) : new Date(year,0)).getTime();
dateRange.endTime = (UTC? new Date(Date.UTC(year+1,0)) : new Date(year+1,0)).getTime() - 1;
return dateRange;
}
var month = dateTime['get' + UTC + 'Month']();
if (/^month$/i.test(rangeValue)) {
var monthStart = UTC? new Date(Date.UTC(year,month)) : new Date(year,month);
dateRange.startTime = monthStart.getTime();
// The setMonth method returns the time value, so no need for getTime
dateRange.endTime = monthStart['set' + UTC + 'Month'](monthStart['get' + UTC + 'Month']() + 1, 1) - 1;
return dateRange;
}
// Add week, day, etc.
}
var dr = generateTimeRange('year', new Date(), false);
console.log('Start: ' + new Date(dr.startTime) + '\nEnd: ' + new Date(dr.endTime));
dr = generateTimeRange('month', new Date(), false);
console.log('Start: ' + new Date(dr.startTime) + '\nEnd: ' + new Date(dr.endTime));
// UTC tests, note if west of GMT will seem to be one day early:
dr = generateTimeRange('year', new Date(), true);
console.log('Start: ' + new Date(dr.startTime) + '\nEnd: ' + new Date(dr.endTime));
dr = generateTimeRange('month', new Date(), true);
console.log('Start: ' + new Date(dr.startTime) + '\nEnd: ' + new Date(dr.endTime));
I would like to put on our company intranet page the number of days until the next payday, however - the payday dates aren't every 4 weeks etc. they will be similar to this:
1st January 2011
15th February 2011
12th March 2011
20th April 2011
...
Is it possible to have a javascript countdown clock that has the above dates listed, so once one date has passed it would then start counting down until the next calendar date?
I can find plenty of examples of scripts that countdown until a specific date but none that start counting down to the second date once the first has passed.
Thanks,
Dan
Put the dates in an array. Be careful, in Javascript the months are zero-based so ranging from 0 to 11. Iterate the array and when the date is bigger then today display the days in between:
var calcPayDate = function () {
var payDates = [];
payDates.push(new Date(2011, 0, 1));
payDates.push(new Date(2011, 1, 15));
payDates.push(new Date(2011, 2, 12));
payDates.push(new Date(2011, 3, 20));
var today = new Date();
for (var i = 0; i < payDates.length; i++) {
if (payDates[i] > today) {
document.getElementById('countdownDiv').innerHTML = calcDays(payDates[i], today);
break;
}
}
}
var calcDays = function(date1, date2) {
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// Convert back to days and return
return Math.round(difference_ms / ONE_DAY)
}
The calcDays function is an function found on this site
The days are put in a div which is called 'countdownDiv'.
Search the web for "JavaScript tutorial".
Meanwhile, here's some code to get you started:
var dates = [
new Date(2011, 0, 1), // note that format is year, month-1, day
new Date(2011, 1, 15), // don't ask me why
new Date(2011, 2, 12),
new Date(2011, 3, 20)
];
var now = new Date();
for (var i in dates) { // this is a foreach loop
if (now < dates[i]) {
document.write(Math.ceil((dates[i] - now) / 86400000));
break;
}
}