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();
Related
I used this code to convert epoch to human readable date
var timestamp = 1293683278;
var date = new Date(timestamp*1000);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
I need to change it to UTC+3 how can i do this ?
Thanks for your help
The Date constructor treats time values as UTC. Date objects only ever represent UTC time, the "local" values produced by toString methods use system settings to determine the offset to use, but that's only for the sake of producing a timestamp, it doesn't change the underlying Date or its time value.
If you want a specific offset, you can choose an appropriate IANA location such as Africa/Nairobi, which is +3 all year round, and produce a timestamp using toLocaleString or Intl.DateTimeFormat, e.g.
console.log(
new Date().toLocaleString('default',{timeZone:'Africa/Nairobi', timeZoneName:'short'})
);
Just curious - but couldn't you just append 3 hours onto your timestamp before formatting it with your existing code. I'm curious if there's some date/calendar subtlety where this wouldn't reliably work.
const THREE_HOURS_IN_MS = 3*60*60*1000;
var date = new Date(timestamp*1000 + THREE_HOURS_IN_MS);
// rest of your code stays unchanged
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
You can use moment.js utcOffset to achieve this easily:
const moment = require("moment");
const timestamp = 1619071948 * 1000;
console.log(moment(timestamp).utcOffset(180).format("YYYY-MM-DDThh:mm:ssZ"));
The offset provided is in minutes
https://momentjs.com/docs/#/manipulating/utc-offset/
I need date algorithms, Which will display me how long I have been given a date anywhere.
Example:
Suppose
Today is 01/06/2019 (dd/mm/yy)
BirthDate is 31/05/2019 (dd/mm/yy)
Now, My age is 1 day 0 Months and 0 years
[NOTE: I need all of them, It means day/month and years]
I have been read at least 23 articles/post in this site but they only give years or month or date but not everything in one...
var date, cDate, cMonth, cYears, oDate, oMonth, oYears;
date = new Date()
//current date
cDate = date.getDate()
cMonth = date.getMonth()
cYears = date.getFullYear()
//birth date
oDate = 01
oMonth = 05
oYears = 2019
(Multiplying is not the main solution I think so, need to work with all arithmetics operator)
This will give you the result you need
var birth = new Date("5/31/2019"); // mm/dd/year
var today = new Date();
var diff = today.valueOf()-birth.valueOf();
var result = new Date(diff);
var dayDiff = result.getDate() - 1; //because epoch start from 1st
var yearDiff = result.getFullYear() - 1970; //because epoch start from 1970
var str = `${dayDiff} day ${result.getMonth()} Months and ${yearDiff} years`;
console.log(str);
You should use moment, so there you can do:
var a = moment("04/09/2019 15:00:00");
var b = moment("04/09/2013 14:20:30");
console.log(a.diff(b, 'years'))
console.log(a.diff(b, 'months'))
console.log(a.diff(b, 'days'))
Similarly, you can get minutes, hours and seconds if you need.
While using the library moment.js
This is my code:
var date1 = '01/02/2017';
var date2 = '31/01/2020';
var startDate = new Date( date1.split("/")[2], date1.split("/")[1]-1, date1.split("/")[0] );
var endDate = new Date( date2.split("/")[2], date2.split("/")[1]-1, date2.split("/")[0] );
var diff = new Date(endDate - startDate);
var diffResult = ((diff.getFullYear() - 1970) * 12+ diff.getMonth()) + " months";
so the output is only 35 months (and also 30 days but its hidden)
but as 30 days are actually already a month, I would like to have it as 36 months.
any suggestions?
thanks
There are several good thoughts/solutions in the comments. It seems what you're really after is the number of 30-day intervals that fit between the start and end date.
After all, 30 days is not always a month as months can have 31 days.
If you're interested in how many 30-day intervals fit between a start and end date you can count the days and divide by 30:
var date1 = '01/02/2017';
var date2 = '31/01/2020';
var dateRegex = /\d+/g;
var date1Array = date1.match(dateRegex);
var date2Array = date2.match(dateRegex);
var startDate = new Date(date1Array[2], date1Array[1], date1Array[0]);
var endDate = new Date(date2Array[2], date2Array[1], date2Array[0]);
var diffResult = Math.round((endDate-startDate)/(1000*60*60*24));
var months = Math.floor(diffResult/30);
alert(months);
Credit for the equation to get the number of days goes to this question.
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.
}
Let's say I have 3 variables like this:
var Month = 8; // in reality, it's a parameter provided by some user input
var Year = 2011; // same here
var FirstDay = new Date(Year, Month, 1);
Now I want to have the value of the day before the first day of the month in a variable. I'm doing this:
var LastDayPrevMonth = (FirstDay.getDate() - 1);
It's not working as planned. What the right of doing it?
Thanks.
var LastDayPrevMonth = new Date(Year, Month, 0).getDate();
var LastDayPrevMonth = new Date(FirstDay);
LastDayPrevMonth.setHours(FirstDay.getHours()-24);
var FirstDay = new Date(Year, Month, 1);
var lastMonth = new Date(FirstDay);
lastMonth.setDate(-1);
alert(lastMonth);
And remember that 8 is Sept, not Aug in JavaScript. :)
If you need to calculate this based on today's date ( you want the last day of last month ), the following should help.
If you only care about the month/day/year, this is the simplest and fastest that I can think of:
var d = new Date(); d.setDate(0);
console.log(d);
If you want midnight of last day of the previous month, then:
var d = new Date(); d.setDate(0); d.setHours(0,0,0,0);
console.log(d);
If you want to know the last day of the previous month, based on provided year/month:
var year = 2016, month = 11;
var d = new Date(year, (month - 1)); d.setDate(0); d.setHours(0,0,0,0);
console.log(d);
After running any of the above, to get the YYYY-M-D format:
var str = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
console.log(str);
To see additional methods available, and to see what they do, you can read the docs.
Create a new Date object and pass it the other date coerced to the number of milliseconds since the Unix epoch and then minus a whole day (in milliseconds).
var LastDayPrevMonth = new Date(FirstDay - 864e5);
Example:
var Month = 8; // in reality, it's a parameter provided by some user input
var Year = 2011; // same here
var FirstDay = new Date(Year, Month, 1);
var LastDayPrevMonth = new Date(FirstDay - 864e5);
document.body.innerHTML = LastDayPrevMonth;