Convert local time to UTC in JavaScript - javascript

i have this code for working with dates.
<script language="javascript" type="text/javascript">
$("#Reports_SignUpDateAfter_container").datepicker({
changeYear: true,
changeMonth: true,
dateFormat: 'dd-mm-yy', //"dd-mm-yy",
gotoCurrent: true,
yearRange: '-10:+10',
onSelect: function() {
Reports_SignUpDateAfter_changeDate(false);
}
});
// react on manual text box editing
$("#Reports_SignUpDateAfter_container").change(function() {
Reports_SignUpDateAfter_changeDate(true);
});
function Reports_SignUpDateAfter_changeDate(manualChange) {
var newDate = $("#Reports_SignUpDateAfter_container").datepicker("getDate");
if (newDate != null) {
// add time information
newDate = DateUtils.copyTimeFrom("#Reports_SignUpDateAfter_local", newDate);
DateUtils.setDate("#Reports_SignUpDateAfter_local", newDate);
// convert local to UTC
Reports_SignUpDateAfter_localToUTC();
if (manualChange) {
$("#Reports_SignUpDateAfter_container").datepicker("setDate", newDate)
}
} else { // empty
$("#Reports_SignUpDateAfter_local").val("");
$("#Reports_SignUpDateAfter").val("");
}
}
// new date as UTC
function Reports_SignUpDateAfter_setDate(newDate) {
// store time into hidden inputs
DateUtils.setDate("#Reports_SignUpDateAfter", newDate);
// set local drop downs and hidden input
var dateString = DateUtils.getString(newDate);
dateString = DateUtils.fromUTCToLocal(dateString);
var localDate = DateUtils.getDateFromString(dateString);
DateUtils.setDate("#Reports_SignUpDateAfter_local", localDate);
$("#Reports_SignUpDateAfter_container").datepicker("setDate", localDate);
};
function Reports_SignUpDateAfter_localToUTC() {
// get string and convert to UTC
var dateString = $("#Reports_SignUpDateAfter_local").val();
dateString = DateUtils.fromLocalToUTC(dateString);
$("#Reports_SignUpDateAfter").val(dateString);
// conversion end
}
;
</script>
Problem is when i chose Start and End date like 2015-11-02 and end date 2015-11-04 it always convert me the date to UTC(-1:00h) but it doesn't consider the winter and summer date changes. For that date is should be the same(UTC and local). Is there any clue why is that so ?
var DateUtils = DateUtils || {
getDate: function (selector) {
var value = $(selector).val();
if (value == null || value == "") {
var date = new Date();
date.setHours(0);
date.setMinutes(0);
date = DateUtils.cleanSeconds(date);
return date;
}
return DateUtils.getDateFromString(value);
},
getClientTimeDifferenceFromUTC: function () {
var d = new Date()
return d.getTimezoneOffset();
},
setDate: function (selector, date) {
if (date != null) {
var old = DateUtils.getDate(selector);
old.setTime(date.getTime());
old = DateUtils.cleanSeconds(old);
$(selector).val(DateUtils.getString(old));
} else {
$(selector).val("");
}
},
// copies time from selector and date part from date
copyTimeFrom: function (selector, date) {
var value = $(selector).val();
if (date != null && value != null && value != "") {
var old = DateUtils.getDate(selector);
date.setHours(old.getHours());
date.setMinutes(old.getMinutes());
}
return date;
},
setHour: function (selector, hour) {
var old = DateUtils.getDate(selector);
old.setHours(hour);
old = DateUtils.cleanSeconds(old);
$(selector).val(DateUtils.getString(old));
},
setMinute: function (selector, minute) {
var old = DateUtils.getDate(selector);
old.setMinutes(minute);
old = DateUtils.cleanSeconds(old);
$(selector).val(DateUtils.getString(old));
},
cleanSeconds: function (date) {
date.setSeconds(0);
date.setMilliseconds(0);
return date;
},
// formats date into yyyy-mm-dd hh:mm format
getString: function (date) {
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
month = ('0' + month).slice(-2);
day = ('0' + day).slice(-2);
hours = ('0' + hours).slice(-2);
minutes = ('0' + minutes).slice(-2);
return year + "-" + month + "-" + day + " " + hours + ":" + minutes;
},
// formats string from yyyy-mm-dd hh:mm into date
getDateFromString: function (date) {
if (date == undefined || date == null) {
return null;
}
var m = date.match(/Date\((\d+)\)/); //handle .NET MVC Date format (i.e. "/Date(1426598616621)/")
if (m) {
return new Date(parseInt(m[1]));
}
var year = date.substring(0, 4);
var month = date.substring(5, 7);
var day = date.substring(8, 10);
var hours = date.substring(11, 13);
var minutes = date.substring(14, 16);
var newDate = new Date(year, month - 1, day, hours, minutes);
// newDate.setYear(year);
// newDate.setDate(1);
// newDate.setMonth(month - 1);
// newDate.setDate(day);
// newDate.setHours(hours);
// newDate.setMinutes(minutes);
newDate = DateUtils.cleanSeconds(newDate);
return newDate;
},
// dateString in format yyyy-mm-dd hh:mm
fromLocalToUTC: function (dateString) {
var date = this.fromLocalToUTCDate(dateString);
return this.getString(date);
},
fromLocalToUTCDate: function (dateString) {
var dateArray = dateString.substring(0, 10).split("-");
var timeArray = dateString.substring(11, 19).split(":");
if (timeArray[0] == null || timeArray[0] == "")
timeArray[0] = 0;
if (timeArray[1] == null || timeArray[1] == "")
timeArray[1] = 0;
var d = new Date(dateArray[0], dateArray[1] - 1, dateArray[2], timeArray[0], timeArray[1], 0);
// *****
// conversion from local date/time to UTC
var offSet = d.getTimezoneOffset() * 60000;
var millis = d.getTime() + offSet;
d.setTime(millis);
// *****
return d;
},
// dateString in format yyyy-mm-dd hh:mm
// returns date as string
fromUTCToLocal: function (dateString) {
var date = this.fromUTCToLocalDate(dateString);
return this.getString(date);
},
// dateString in format yyyy-mm-dd hh:mm
// returns date object
fromUTCToLocalDate: function (dateString, setOffset) {
var dateArray = dateString.substring(0, 10).split("-");
var timeArray = dateString.substring(11, 19).split(":");
if (timeArray[0] == null || timeArray[0] == "")
timeArray[0] = 0;
if (timeArray[1] == null || timeArray[1] == "")
timeArray[1] = 0;
var d = new Date(dateArray[0], dateArray[1] - 1, dateArray[2], timeArray[0], timeArray[1], 0);
// *****
// conversion from UTC to local date/time
if (setOffset != false) {
var offSet = d.getTimezoneOffset() * 60000;
var millis = d.getTime() - offSet;
d.setTime(millis);
}
// *****
return d;
},

Related

remove timezone in my random date generator in javascript

This is my code. I make it random but the timezone is always in there and i dont know how to disappear the timezone, can someone help me with this I'am beginner in this thanks
var startDate = new Date("1990-01-01"); //YYYY-MM-DD
var endDate = new Date("2022-01-01"); //YYYY-MM-DD
function formatDate(date) {
const year = date.getFullYear();
/* getMonth returns dates from 0, so add one */
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month < 10 ? '0' : ''}${ month }-${ day < 10 ? '0' : '' }${day}`
}
var getDateArray = function(start, end) {
return new Date(
start.getTime() + Math.random() * (end.getTime(0) - start.getTime(0))
);
}
var dateArr = getDateArray(startDate, endDate);
console.log(dateArr);
If you call the formatDate function you have in your code, I believe that will get rid of the timezone information.
var startDate = new Date("1990-01-01"); //YYYY-MM-DD
var endDate = new Date("2022-01-01"); //YYYY-MM-DD
function formatDate(date) {
const year = date.getFullYear();
/* getMonth returns dates from 0, so add one */
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month < 10 ? '0' : ''}${ month }-${ day < 10 ? '0' : '' }${day}`
}
var getDateArray = function(start, end) {
return formatDate(new Date(
start.getTime() + Math.random() * (end.getTime(0) - start.getTime(0))
));
}
var dateArr = getDateArray(startDate, endDate);
console.log(dateArr);
All I did here was add a call to your formatDate function within the getDateArray function so that now the return of the getDateArray will no longer contain timezone information.
Create these 2 functions to change the date format.
function DateFormat(startDate)
{
const strYear = date("Y",strtotime(strDate));
const strMonth= date("n",strtotime(strDate));
const strDay= date("j",strtotime(strDate));
return "${strYear}$-${strMonth}-${strDay}";
}
function DateFormat(endDate)
{
const strYear = date("Y",strtotime(strDate));
const strMonth= date("n",strtotime(strDate));
const strDay= date("j",strtotime(strDate));
return "${strYear}$-${strMonth}-${strDay}";
}

discord.js if date.now() function

I'm trying to get the current date (day, hour, minute, second) and put it in an if() statement to compare it with the date entered. But how am I able to get the date and ask for it in code?
This is what I got so far:
bot.on("ready", () => {
var today = new Date();
var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
var time = today.getHours() + ":" + today.getMinutes();
var currentdate = date + time
var endDate = new Date('2021-01-21T14:00:00')
if (endDate = currentdate) {
console.log('The time has come..')
} else {
console.log('The time is coming soon..')
}
})
you can use 'moment.js' like this :
const moment = require("moment");
getDifferenceInYear(date_1, date_2) {
return moment(date_1).diff(moment(date_2), "years");
}
getDifferenceInDay(date_1, date_2) {
return moment(date_1).diff(moment(date_2), "days");
}
getDifferenceInHour(date_1, date_2) {
return moment(date_1).diff(moment(date_2), "hour");
}
getDifferenceInSecond(date_1, date_2) {
return moment(date_1).diff(moment(date_2), "second");
}
isNowBetween(startDate, endDate) {
return moment(new Date()).isBetween(startDate, endDate);
}
you can following this code for comparing:
let inputDate = '2021-01-21T14:00:00'
let endDate = Math.round(new Date(inputDate ) / 1000);
let cuurentDate = Math.round(new Date() / 1000)
if (cuurentDate == endDate ) {
console.log('The time has come..')
}
else {
console.log('The time is coming soon..')
}

Expand date range using JS?

I have this variable {{ $daterange }} with json like this
{
"starts_at": "2020-05-20",
"ends_at": "2020-05-23"
},
{
"starts_at": "2020-05-24",
"ends_at": "2020-05-26"
},
{
"starts_at": "2020-05-27",
"ends_at": "2020-05-29"
}
What I want to do is to expand something like this,
2020-05-20
2020-05-21
2020-05-22
2020-05-23
2020-05-24
2020-05-25
2020-05-26
2020-05-27
2020-05-28
2020-05-29
I'm planning to assign these dates inside of expandedDate variable
var expandedDate = [ ....dates ];
This should be done using jquery/js
UPDATE*
Recently this code works and can get all dates between 2 dates. It will list down all dates between 2 date range written in the code.
// Returns an array of dates between the two dates
var getDates = function(startDate, endDate) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate, 1);
}
return dates;
};
// Usage
var dates = getDates(new Date(2013,10,22), new Date(2013,11,25));
dates.forEach(function(date) {
console.log(date);
});
How can I populate {{ $daterange }} contains multiple date range.
Think I missed your update with existing code. The following code seems to get the desired output using javascript. Just added comments to each step as an explanation. Hope it is helpful.
//sample input data
var daterange = [{
"starts_at": "2020-05-27",
"ends_at": "2020-06-23"
},
{
"starts_at": "2020-05-24",
"ends_at": "2020-05-26"
},
{
"starts_at": "2020-05-27",
"ends_at": "2020-05-29"
}
];
// function to get dates between two dates
var getDaysAsArray = function(start_date, end_date) {
for (var arr = [], d = new Date(start_date); d <= end_date; d.setDate(d.getDate() + 1)) {
arr.push(new Date(d));
}
return arr;
};
// function to convert date into the format yyyy-mm-dd
var getFormattedDay = function(date) {
day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
month = date.getMonth()+1 < 10 ? "0" + (date.getMonth()+1) : date.getMonth()+1;
year = date.getFullYear();
return year + "-" + month + "-" + day;
}
//main logic
var expandedDate = [];
//Iterate through the list of arrays in the date range
for (var key in daterange) {
//get first pair of from and to date
var from_string = daterange[key].starts_at;
var to_string = daterange[key].ends_at;
// convert the string date to date format for from and to.
var from_date = new Date(from_string.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3"));
var to_date = new Date(to_string.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3"));
// call getDaysAsArray to convert dates into strings and into an array.
var daylist = getDaysAsArray(from_date, to_date);
// iterate through the daylist and push it into the final array you want to use
for (var day in daylist) {
expandedDate.push(getFormattedDay(daylist[day]));
}
}
// final result required
console.log(expandedDate);
Here's the complete code on how to solve this question
Based on #thommu
var daterange = [
{
"starts_at": "2020-05-24",
"ends_at": "2020-05-26"
},
{
"starts_at": "2020-05-27",
"ends_at": "2020-05-29"
}
];
// function to get dates between two dates
var getDaysAsArray = function(start_date, end_date) {
for (var arr = [], d = new Date(start_date); d <= end_date; d.setDate(d.getDate() + 1)) {
arr.push(new Date(d));
}
return arr;
};
// function to convert date into the format yyyy-mm-dd
var getFormattedDay = function(date) {
day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
month = date.getMonth() < 10 ? "0" + date.getMonth() : date.getMonth();
year = date.getFullYear();
return year + "-" + month + "-" + day;
}
//main logic
var expandedDate = [];
//Iterate through the list of arrays in the date range
for (var key in daterange) {
//get first pair of from and to date
var from_string = daterange[key].starts_at;
var to_string = daterange[key].ends_at;
// convert the string date to date format for from and to.
var xfrom_date = new Date(from_string.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3"));
var xto_date = new Date(to_string.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3"));
//Add +1 month to correct the data
var from_date = new Date(xfrom_date.setMonth(xfrom_date.getMonth()+1));
var to_date = new Date(xto_date.setMonth(xto_date.getMonth()+1));
// call getDaysAsArray to convert dates into strings and into an array.
var daylist = getDaysAsArray(from_date, to_date);
// iterate through the daylist and push it into the final array you want to use
for (var day in daylist) {
expandedDate.push(getFormattedDay(daylist[day]));
}
}
//Filter Duplicated Dates
var dateDuplicate = expandedDate;
var uniqueDate = [];
$.each(dateDuplicate, function(i, el){
if($.inArray(el, uniqueDate) === -1) uniqueDate.push(el);
});
// final result required
console.log(uniqueDate);

Parse String Time to JS Date Obj

I am trying to convert a string of time such as "7:30am" to JavaScript Date Object like Sat Nov 18 2017 7:30:00 GMT-0500 (EST)
My approach:
function dateObj(d) { // date parser ...
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') parts[0] = (+parts[0]) + 12;
date.setHours(+parts.shift());
date.setMinutes(+parts.shift());
return date
}
var startTime = "7:30";
var endTime = "9:30pm";
var startDate = dateObj(startTime); // get date objects
var endDate = dateObj(endTime);
console.log(startDate, endDate)
I got Invalid Date for both startDate, endDate.
Try here:
function dateObj(d) { // date parser ...
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') {
parts[0] = parts[0] + 12;
}
date.setHours(parts.shift());
date.setMinutes(parts.shift());
return date
}
var startTime = "7:30am";
var endTime = "9:30pm";
var now = new Date();
var startDate = dateObj(startTime); // get date objects
var endDate = dateObj(endTime);
var test = dateObj(startTime)
console.log(startDate, endDate)
I would rather use a regular expression to extract the date elements and also add some error handling for the case the date format is not valid.
And do not forget also to handle 12am and 12pm. This needs extra handling in the code.
See below:
function dateObj(d) { // date parser ...
const rx = /(\d{1,2})\:(\d{1,2})\s*(am|pm)/g;
const parts = rx.exec(d);
if (parts === null) {
return "Not a valid date: " + d;
}
date = new Date();
const amPm = parts.pop().toLowerCase();
const hour = parseInt(parts[1]);
if (amPm === 'pm') {
if (hour !== 12) {
parts[1] = (parseInt(parts[1])) + 12;
}
} else if (amPm === 'am' && hour === 12) {
parts[1] = 0;
}
date.setHours(parts[1]);
date.setMinutes(parts[2]);
return date
}
var startTime = "7:30";
var endTime = "9:30pm";
var startDate = dateObj(startTime); // get date objects
var endDate = dateObj(endTime);
console.log(startDate, endDate)
console.log(dateObj("7:30 pm"))
console.log(dateObj("7:30 am"))
console.log(dateObj("7:30am"))
console.log(dateObj("12:30pm"))
console.log(dateObj("12:30 am"))
This is working for me if you enter 9:30 pm instead of 9:30pm, the white space needs to be there for regex:
function dateObj(d) {
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') {
parts[0] = parts[0] + 12;
}
date.setHours(parts[0]);
date.setMinutes(parts[1]);
return date;
}
It just needs a space before am/pm :
d = t => new Date(new Date().toDateString() + t.replace(/(.*\d)/, " $1 "))
console.log(d("7:30").toString())
console.log(d("7:30am").toString())
console.log(d("9:30pm").toString())
This will create a new Date object that includes the current time.
But it is based on the timezone of where the code is run.
var timeRe = /(\d+):(\d+)([amp]*)/gi;
function timeParse(time) {
var today = new Date();
var match = time.split(timeRe);
console.log(time, match);
if (match) {
var hours = parseInt(match[1],10)+(match[3].toLowerCase()==='pm'?12:0)%24;
today.setHours(hours);
today.setMinutes(parseInt(match[2],10));
today.setSeconds(0);
}
return today;
}
var startTime = "7:30";
var endTime = "9:30pm";
var startDate = timeParse(startTime); // get date objects
var endDate = timeParse(endTime);
console.log(startDate, endDate)

convert '18/10/2016 10:31:22PM' format into '18/10/2016 22:31:22' time format in javascript

var now = new Date('18/10/2016 10:31:22PM');
var time = now.toLocaleTimeString();
alert(time);
this function give an output invalid date. I want to convert this "18/10/2016 22:31:22" format. give me an appropriate example as a solution.
this function should work for your date format
function convertDate(date_string){
var d = date_string.trim();
d = d.split(" ");
v = d[1].split(":")[0];
v = d[1].indexOf("PM")>-1 ? +v+12 : v;
d[1] = d[1].replace(d[1].split(":")[0],v);
d = d.join(" ").replace("PM","").replace("AM","");
return d;
}
console.log(convertDate("18/10/2016 10:31:22PM"));
console.log(convertDate("01/10/2016 09:31:22PM"));
console.log(convertDate("06/10/2016 2:31:22AM"));
console.log(convertDate("07/10/2016 7:31:22AM"));
Without using a library, you will need to extract all the date tokens and send them into a new date object in the correct order. From there, you can create your own date formatting function.
var DATE_FORMAT = /(\d{1,2})\/(\d{1,2})\/(\d{4}) (\d{1,2}):(\d{2}):(\d{2})([AP]M)/;
var dateStr = '18/10/2016 10:31:22PM';
var now = parseDateString(dateStr, DATE_FORMAT, function(tokens) {
return [
parseInt(tokens[3], 10), // year
parseInt(tokens[2], 10) - 1, // month
parseInt(tokens[1], 10), // date
to24(parseInt(tokens[4], 10), tokens[7]), // hours, meridiem
parseInt(tokens[5], 10), // minutes
parseInt(tokens[6], 10), // seconds
0 // milliseconds
];
});
document.body.innerHTML = formateDate(now);
function parseDateString(dateStr, dateFormat, func) {
var tokens = dateStr.match(dateFormat);
var args = Array.prototype.concat.apply([null], func(tokens));
return new (Function.prototype.bind.apply(Date, args));
}
function formateDate(date, dateSeparator) {
return [
pad2(date.getDate()),
pad2(date.getMonth() + 1),
date.getFullYear()
].join(dateSeparator || '/') + ' ' + [
pad2(date.getHours()),
pad2(date.getMinutes()),
pad2(date.getSeconds())
].join(':');
}
function pad2(str) { return ('00' + str).substr(-2); }
function to24(hours, meridiem) {
switch (meridiem) {
case 'PM': if (hours < 12) return hours + 12;
case 'AM': if (hours === 12) return hours - 12;
default: return hours;
}
}
Of course, this can be done in moment with one line.
var dateStr = '18/10/2016 10:31:22PM';
var time = moment(dateStr, 'DD/MM/YYYY hh:mm:ssA').format('DD/MM/YYYY HH:mm:ss');
document.body.innerHTML = time;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>

Categories