Sorry, but what is the fastest way to display the current date?
2014-01-18 Saturday 12:30
with this function or how do it the right way?
var d=new Date();
var t=d.getTime();
Try
var d = new Date();
var dd = d.getDate();
var mm = d.getMonth()+1; //January is 0!
var yy = d.getFullYear();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
var day=weekday[d.getDay()];
var h = d.getHours();
var m = d.getMinutes();
alert(yy+"-"+mm+"-"+dd+" "+day+" "+h+":"+m)
DEMO
var d = new Date();
alert(d.toString());
If you don't mind the format, you can do it in one line:
''+new Date()
You only need to use a Date object as a string, in order to implicitly call its .toString() method, which
returns a String value. The contents of the String are
implementation-dependent, but are intended to represent the Date in
the current time zone in a convenient, human-readable form.
new Date().toGMTString()
It's something similar to what you are looking for
If you want complicate the output you can get element by element and format yourself the date (or you can use Globalize.js)
Related
so I got this function that adds 5 days to the current date, the only problem is that the date is displayed as "Mon May 30 2022 00:16:04 GMT+0300 (Eastern European Summer Time)" I need a simple, clean format like 22/07/2002.
<div class="container-date">
<p>Offer expires on <span id="date"></span></p>
</div>
ar d = new Date();
d.setDate(d.getDate() + 10);
document.getElementById("date").innerHTML = d ;
SUGGESTION
You can use formatDate(date, timeZone, format) method to easily format date objects. See this quick sample below:
SCRIPT
function test() {
var d = new Date();
var formattedDate = Utilities.formatDate(new Date(d.setDate(d.getDate() + 5)), Session.getScriptTimeZone(), "dd/MM/yyyy")
console.log(formattedDate);
}
Demo:
date.toISOString().slice(0, 10): Convert date to string and get first 10 character.
toISOString() (2022-05-29T23:03:31.782Z to 2022-05-29)
date.split('-').reverse().join('/'): Split string by -, reverseit for formatting and convert array to a string with / separator. (2022-05-29 to 29/05/2022)
const addDays = (days) => {
let date = new Date();
date.setDate(date.getDate() + days);
date = date.toISOString().slice(0, 10);
return date.split('-').reverse().join('/');
}
const date = addDays(5);
console.log(date);
Format Date and add days to it
function formatDate(days = 10) {
const dt = new Date();
Logger.log(Utilities.formatDate(new Date(dt.getFullYear(),dt.getMonth(),dt.getDate() + days),Session.getScriptTimeZone(),"dd/MM/yyyy"));
}
Execution log
5:11:55 PM Notice Execution started
5:11:54 PM Info 03/06/2022
5:11:56 PM Notice Execution completed
Try this
// Note this wont calculate 5days ahead ,it just gives the asked format!
var today = new Date();
var dd = String(today.getDate()).padStart(2,'0');
to the current date
var mm = String(today.getMonth()+1).padStart(2,'0');
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
console.log(today);
This should work if the days overflow with the months.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Add Days to Date</title>
</head>
<body>
<div class="container-date">
<p>Offer expires on <span id="date"></span></p>
</div>
<script>
//Date class
var d = new Date();
//Returns the current day
var day = d.getDate();
//Returns the current month
var month = d.getMonth();
//Returns the current year
var year = d.getFullYear();
//New Date Class for the current date plus added days
//Days overflowing will make a new month and a new year if needed
//see "https://www.w3schools.com/js/js_dates.asp" for more info
var newDate = new Date(year, month, day+5);
//month indexes are 0-11 for Jan-Dec, so the added one is necessary
var dd = newDate.getDate();
var mm = newDate.getMonth()+1;
var yyyy = newDate.getFullYear();
//for the double digit string
dd = dd.toString().padStart(2,"0");
mm = mm.toString().padStart(2,"0");
//Date string Message
var dateString = `${dd}/${mm}/${yyyy}`;
document.getElementById("date").innerHTML = dateString;
</script>
</body>
</html>
I have a UTC date string -> 10/30/2014 10:37:54 AM
How do I get the timestamp for this UTC date? As far as I know, following is handling this as my local time
var d = new Date("10/30/2014 10:37:54 AM");
return d.getTime();
Thank you
You can use Date.UTC to create a UTC format date object.
Reference:
Stackoverflow
MDN
(function() {
var d = new Date();
var d1 = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds()));
console.log(+d);
console.log(+d1);
})()
You can decrease the "TimezoneOffset"
var d = new Date("10/30/2014 10:37:54 AM");
return d.getTime() - (d.getTimezoneOffset() *1000 * 60);
Also u can use the UTC function
var d = new Date("10/30/2014 10:37:54 AM");
return Date.UTC(d.getFullYear(),d.getMonth()+1,d.getDate(),d.getHours(),d.getMinutes(),d.getSeconds());
If the format is fixed, you could easly parse it and use the Date.UTC() API.
A quick hack would be to append UTC to the end of your string before parsing:
var d = new Date("10/30/2014 10:37:54 AM UTC");
But I would advise you to use a library like moment.js, it makes parsing dates much easier
Try Date.parse
var d = new Date("10/30/2014 10:37:54 AM");
var timstamp = Date.parse(d) / 1000;
Hope this helps:
Date date= new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");
date = sdf.parse(date.toString());
String timestamp = sdf2.format(date);
I'm trying to convert UTC time to local time, but the below code is not working. What's wrong in it?
var parsedStartDateTime =
new Date(moment.unix(parseInt(data['StartDateTime'].substr(6)) / 1000));
var startDateTimeMoment =
moment.tz(parsedStartDateTime, tzName);
var formatted_date =
startDateTimeMoment.format("MMM DD YYYY h:mm:ss A");
To format your date try this:
var d = new Date();
var formatD = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");
Reference: Javascript to convert UTC to local time
Try appending UTC to the string before converting it to a date then use toString() method of date.
Example:
var myDate = new Date('7/1/2014 5:22:55 PM UTC');
date.toString(); //this should give you local date and time
This code was taken from here
Here is my solution:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
date.toLocaleString().replace(/GMT.*/g,"");
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.
}
I have a date which is provided as a string such as 09/12/2012.
If the string is today, I wish to display "Today", else I wish to display 09/12/2012.
The problem with my approach shown below is that a month like 09 gets parsed to 0 and not 9.
What is the best way to do this? Thank you
var currentDate = new Date();
dateText='09/12/2012';
var a=dateText.split('/');// mdY
$("#date").text(((parseInt(a[0])-1==currentDate.getMonth()&&parseInt(a[1])==currentDate.getDate()&&parseInt(a[2])==currentDate.getFullYear())?'Today':dateText));
Pass a second argument to parseInt() - specifically, 10.
$("#date").text(((parseInt(a[0], 10)-1==currentDate.getMonth()&&parseInt(a[1], 10)==currentDate.getDate()&&parseInt(a[2], 10)==currentDate.getFullYear())?'Today':dateText));
The second argument tells the function the base to use for interpreting the expression. If you don't pass that explicitly, it uses the old C conventions, which will lead to numbers starting with a zero to be interpreted as base 8 constants. That causes problems for 08 and 09.
Here's a fiddle: http://jsfiddle.net/pfHA7/1/
function today()
{
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} var today = mm+'/'+dd+'/'+yyyy;
return today;
}
var dateText = '09/12/2012';
$("#date").text( today() == dateText ? 'Today' : dateText );