Javascript OO Function - javascript

I need something obvious pointing out to me in regard to JS functions.
The following code works, but I want to call upon it anywhere:
var pattern = /(\d{2})\-(\d{2})\-(\d{4})/;
var date = entry.date.split(' ');
var date = date[0];
var date = new Date(date.replace(pattern,'$3-$2-$1'));
var year = date.getYear();
var month = date.getMonth();
var day = date.getDay();
What would be the best practice to place this in a global function so I can just do adjustDate(string). Double points (Sadly, not in my power) to explain how I would then also have access to all the objects such as year, month, day.
Thanks in advance!

Can't you just declare the function?
function adjustDate(entry) {
var date = entry.date.split(' ');
date = date[0];
date = new Date(date.replace(/(\d{2})\-(\d{2})\-(\d{4})/, '$3-$2-$1'));
return {
year: date.getYear(),
month: date.getMonth(),
day: date.getDay()
};
}

I would just return a date without abstracting its existing methods
function AdjustedDate(dateString)
{
return new Date(dateString.split(' ')[0].replace(/(\d{2})\-(\d{2})\-(\d{4})/, '$3-$2-$1'));
}
var ad = AdjustedDate(entry.date);
alert(ad);
alert(ad.getDay());

Pass the entry into the function and then pass an object containing the information you want out. Then just access it like you would an ordinary JS object.
function adjustDate(entry) {
var pattern = /(\d{2})\-(\d{2})\-(\d{4})/;
var date = entry.date.split(' ');
var date = date[0];
var date = new Date(date.replace(pattern,'$3-$2-$1'));
var year = date.getYear();
var month = date.getMonth();
var day = date.getDay();
return { day: day, month: month, year: year }
}
var dateObject = adjustDate(/*entry*/)
dateObject.day // day
dateObject.month // month

Related

Get name of the month [duplicate]

It's possible to do this to get the localized full month name using native javascript.
var objDate = new Date("10/11/2009"),
locale = "en-us",
month = objDate.toLocaleString(locale, { month: "long" });
But this only gets the month number for a given date. I'd simply like to get the month name corresponding to a month number. For example, if I do getMonth(2) it would return February. How can I implement getMonth using native javascript(no libraries like moment)?
You are already close:
var getMonth = function(idx) {
var objDate = new Date();
objDate.setDate(1);
objDate.setMonth(idx-1);
var locale = "en-us",
month = objDate.toLocaleString(locale, { month: "long" });
return month;
}
console.log(getMonth(1));
console.log(getMonth(12));
To get all the months of a year and days of the week, loop over a set of dates and use toLocaleString with appropriate options to get the required values:
function getLocalDayNames() {
let d = new Date(2000,0,3); // Monday
let days = [];
for (let i=0; i<7; i++) {
days.push(d.toLocaleString('default',{weekday:'long'}));
d.setDate(d.getDate() + 1);
}
return days;
}
console.log(getLocalDayNames());
function getLocalMonthNames() {
let d = new Date(2000,0); // January
let months = [];
for (let i=0; i<12; i++) {
months.push(d.toLocaleString('default',{month:'long'}));
d.setMonth(i + 1);
}
return months;
}
console.log(getLocalMonthNames());
The language default means toLocaleString uses the default language of the implementation that the code is running in.

Converting C# date-time function to Javascript

I have an application in which I use a couple of date/time manipulation function to populate a couple of calendars. Basically, a user selects a month/year from a dropdown (say, March 2019) and I populate the calendars with 03/01/2019 and 03/31/2019.
I wanted to do this client side so tried to convert those function to javascript and I am getting strange results and can't see what I am doing wrong.
This is the original C# functions I defined and used:
public static DateTime FirstDayOfMonth(this DateTime dt)
{
return new DateTime(dt.Year, dt.Month, 1);
}
public static DateTime LastDayOfMonth(this DateTime dt)
{
DateTime dtFirstDayOfMonth = new DateTime(dt.Year, dt.Month, 1);
DateTime dtLastDayOfMonth = dtFirstDayOfMonth.AddMonths(1).AddDays(-1);
return dtLastDayOfMonth;
}
I called these like below:
DateTime dtSelected = DateTime.Today.AddMonths(int.Parse(ddlMonth.SelectedValue)).AddYears(-1);
dtStartDate = Utils.FirstDayOfMonth(dtSelected);
dtEndDate = Utils.LastDayOfMonth(dtSelected);
The dropdown list is populated like:
for (int i = 12; i >= 1; i--)
{
string s = DateTime.Now.AddYears(-1).AddMonths(i).ToString("Y");
ListItem li = new ListItem(s, i.ToString());
ddlMonth.Items.Add(li);
}
The dropdown entries would look like:
May, 2019 -- value of 12
April, 2019 -- value of 11
....
July, 2018 -- value of 2
June, 2018 -- value of 1
This is my attempt at translating to javacript:
function firstDayOfMonth(dt) {debugger
var year = dt.getFullYear();
var month = dt.getMonth();
var day = dt.getDate();
return new Date(year, month, 1);
}
function lastDayOfMonth(dt) {debugger
var year = dt.getFullYear();
var month = dt.getMonth();
var day = dt.getDate();
var firstDayOfMonth = new Date(year, month, 1);
var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1); --> shows error when called; Object doesn't support property or method 'AddMonths'
return lastDayOfMonth;
}
$(document).on('change', '#ddlMonth', function () {debugger
var monthID = this.value;
var ddlMonth = $('#ddlMonth');
var today = new Date();
var startDate = new Date();
var endDate = new Date();
var dtSelected = new Date();
if (ddlMonth.val() == "")
{
....
}
else
{debugger
dtSelected.setMonth(dtSelected.getMonth() + ddlMonth.val() + 1); -- this becomes "Wed Oct 12, 2360" if I select "March, 2019" from dropdown!
dtSelected.setFullYear(dtSelected.getFullYear() - 1);
dtStartDate = firstDayOfMonth(dtSelected);
dtEndDate = lastDayOfMonth(dtSelected);
}
you have some problem in your code, this for example:
dtSelected.setMonth(dtSelected.getMonth() + ddlMonth.val() + 1); -- this becomes August of 2036!
you take today's month which is the 5 then add to itsome value from your slect and add 1 more and this is a lot of monthes to add.
I think you need to changesome things and do this like this:
change the select values to be the date of the first day of each month and not just number:
for (int i = 12; i >= 1; i--)
{
DateTime date = DateTime.Now.AddYears(-1).AddMonths(i);
ListItem li = new ListItem(date.ToString("Y"), date.ToString("yyyy-MM-01"));
ddlMonth.Items.Add(li);
}
in this format you can use it on js with no problem.
now for your js function:
function lastDayOfMonth(dt) {debugger
var year = dt.getFullYear();
var month = dt.getMonth();
var day = dt.getDate();
var lastDayOfMonth = new Date(year, month, 1);
lastDayOfMonth.setMonth(lastDayOfMonth.getMonth() + 1);
lastDayOfMonth.setDate(lastDayOfMonth.getDate() - 1);
return lastDayOfMonth;
}
$(document).on('change', '#ddlMonth', function () {debugger
var ddlMonth = $('#ddlMonth');
dtStartDate = new Date(ddlMonth.val());
dtEndDate = lastDayOfMonth(dtStartDate);
}

JavaScript forEach. String elements to date

I have an array of strings scheduleDates:
0:"24.04.2016, 11:53"
1:"12.04.2016, 10:07"
2:"13.04.2016, 9:45"
I need to replace the string elements to Date type in the same array.
I tried:
scheduleDates.forEach(function (date) {
var currDate = date.split(', ')[0];
var currTime = date.split(', ')[1];
var hours = currTime.split(':')[0];
var minutes = currTime.split(':')[1];
var year = currDate.split('.')[2];
var month = currDate.split('.')[1];
var day = currDate.split('.')[0];
var newDate = new Date(year, month, day, hours, minutes);
date = newDate;
});
It doesn't work
First of all you should use map instead of forEach. It better fits your purpose.
Here is what I would do (by following your initial thoughts):
function toDateObject(date) {
var currDate = date.split(', ')[0];
var currTime = date.split(', ')[1];
var hours = currTime.split(':')[0];
var minutes = currTime.split(':')[1];
var year = currDate.split('.')[2];
var month = currDate.split('.')[1];
var day = currDate.split('.')[0];
return new Date(year, month, day, hours, minutes);
}
var scheduleDates = ["24.04.2016, 11:53","12.04.2016, 10:07","13.04.2016, 9:45"].map(toDateObject);
Array.prototype.map applies the function given as argument to each element of the array and the collects all the result in a new array which is the result.
In this case it receives an array of strings, applies the toDateObject function to each of them and then returns a new array of the results of that function calls.
Read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
date is a variable that is local to every function call. You're assigning to this local variable, not the position in the array.
An ugly fix is to assign the new value to the correct index. This is a bit hacky, and generally not what forEach is intended for.
scheduleDates.forEach(function (date, index) {
var currDate = date.split(', ')[0];
var currTime = date.split(', ')[1];
var hours = currTime.split(':')[0];
var minutes = currTime.split(':')[1];
var year = currDate.split('.')[2];
var month = currDate.split('.')[1];
var day = currDate.split('.')[0];
var newDate = new Date(year, month, day, hours, minutes);
scheduleDates[index] = newDate;
});
You could instead use map, and assign the resulting array back into your variable.
scheduleDates = scheduleDates.map(function (date) {
// ...
return newDate;
});
Or roll your own destructive map, to make things a little easier.
function mapd (array, block) {
var length = array.length;
for (var i = 0; i < length; i++) {
array[i] = block(array[i], i);
}
}
mapd(scheduleDates, function (date) {
// ...
return newDate;
});
var scheduleDates = ["24.04.2016, 11:53","12.04.2016, 10:07","13.04.2016, 9:45"];
scheduleDates = scheduleDates.map(function (date) {
var currDate = date.split(', ')[0];
var currTime = date.split(', ')[1];
var hours = currTime.split(':')[0];
var minutes = currTime.split(':')[1];
var year = currDate.split('.')[2];
var month = currDate.split('.')[1];
var day = currDate.split('.')[0];
return new Date(year, month-1, day, hours, minutes);
});

Get today date in Google Apps Script

How do I get the Today date on google appscript?
I need to write a code to input today´s date in a cell.
function changeDate(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
var date = //Today´s date!?!?!!?
var endDate = date;
sheet.getRange(5, 2).setValue(endDate);
}
Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")
You can change the format by doing swapping the values.
dd = day(31)
MM = Month(12) - Case sensitive
yyyy = Year(2017)
function changeDate() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
// You could use now Date(); on its own but it will not look nice.
var date = Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")
var endDate = date
}
The Date object is used to work with dates and times.
Date objects are created with new Date()
var now = new Date();
now - Current date and time object.
function changeDate() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
var date = new Date();
sheet.getRange(5, 2).setValue(date);
}
Google Apps Script is JavaScript, the date object is initiated with new Date() and all JavaScript methods apply, see doc here
The following can be used to get the date:
function date_date() {
var date = new Date();
var year = date.getYear();
var month = date.getMonth() + 1; if(month.toString().length==1){var month =
'0'+month;}
var day = date.getDate(); if(day.toString().length==1){var day = '0'+day;}
var hour = date.getHours(); if(hour.toString().length==1){var hour = '0'+hour;}
var minu = date.getMinutes(); if(minu.toString().length==1){var minu = '0'+minu;}
var seco = date.getSeconds(); if(seco.toString().length==1){var seco = '0'+seco;}
var date = year+'·'+month+'·'+day+'·'+hour+'·'+minu+'·'+seco;
Logger.log(date);
}
Easiest way, you can use javascript date object which is new Date().
function changeDate(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
var date = new Date();
sheet.getRange(5, 2).setValue(date);
}
But then you will get the whole time object. You just need to change the format in spreadsheet to time or date, whatever you like.
function myFunction() {
var sheetname = "DateEntry";//Sheet where you want to put the date
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetname);
// You could use now Date(); on its own but it will not look nice.
var date = Utilities.formatDate(new Date(), "GMT+5:30", "yyyy-MM-dd");
//var endDate = date;
sheet.getRange(sheet.getLastRow() + 1,1).setValue(date); //Gets the last row which had value, and goes to the next empty row to put new values.
}

Getting day of the week from timestamp using JavaScript

How do I get the day of the week from a timestamp in JavaScript?
I'd like to get this from a timestamp I specify, not the current date.
Thanks
var timestamp = 1400000000;
var a = new Date(timestamp*1000);
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var dayOfWeek = days[a.getDay()]
Now the "day of the week" is in the dayOfWeek variable.
var timestamp = 654524560; // UNIX timestamp in seconds
var xx = new Date();
xx.setTime(timestamp*1000); // javascript timestamps are in milliseconds
document.write(xx.toUTCString());
document.write(xx.getDay()); // the Day
2020 Update
If this browser support is acceptable for you you can use this one liner:
new Date(<TIMESTAMP>).toLocaleDateString('en-US', { weekday: 'long' }); // e.g. Tuesday
Similar to klidifia's answer, but for some reason the day of the week was off. I had to update the 'days' array to start on Monday.
var timestamp = 1400000000;
var a = new Date(timestamp*1000);
var days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday', 'Sunday'];
var dayOfWeek = days[a.getDay()]
Try out the following:
var currentTime = new Date();
var day = currentTime.getDate();

Categories