I have a JavaScript function running in Google Drive folder of many spreadsheets that is currently logging dates into the log;
function convertDates(){
var ui = SpreadsheetApp.getUi();
SpreadsheetApp.getActiveSpreadsheet().toast('Conversion Started With First Row Date Cells','Conversion', 5);
Logger.log('Date Conversion Started');
var activeCell = SpreadsheetApp.getActiveSpreadsheet().getActiveCell();
var cell = activeCell.getValue();
Logger.log(cell);
}
How would one convert the output of 'cell' which currently looks like:
May 03, 2014 at 05:19PM
Into a Unix Time stamp within Javascript? I am inclined to believe that this can involve the Date() function but am unsure.
Thank's in Advance.
You can do this way to remove "at" and the sheet then recognizes the value as a valid date.
function convertDates(){
var sheet = SpreadsheetApp.getActiveSheet();
var range_input = sheet.getRange(1, 1);
range_input = range_input.getValue();
range_input = range_input.replace("at ", " ");
sheet.getRange(1, 1).setValue(range_input);
}
I am just replacing for one single cell. You can loop that to all the needed cell values.
Hope that helps!
If you want the get a string representation of the number of seconds since the UNIX epoch (january 1, 1970) you can use a code like this :
function convertDates(){
var ui = SpreadsheetApp.getUi();
SpreadsheetApp.getActiveSpreadsheet().toast('Conversion Started With First Row Date Cells','Conversion', 5);
Logger.log('Date Conversion Started');
var activeCell = SpreadsheetApp.getActiveSpreadsheet().getActiveCell();
var unixEpoch = new Date(1970,0,1,0,0,0).getTime();// difference between JS epoch and UNIX epoch in milliseconds
var cell = ((activeCell.getValue().getTime()-unixEpoch)/1000).toString();
Logger.log(cell);
activeCell.setValue(cell);// this will write it back to the sheet... be careful, it is not a date object anymore but a string... so the code won't work after that.
}
You have to remove "at" and to add a space after "05:19".
Look like this :
var date = new Date("May 03, 2014 05:19 PM");
Related
I am trying to convert data stored in "dd.mm.yy" format to "w" format in Google Sheets/Appscript. Unfortunately I cannot use the ".formatDate()" function since sheets does not recognice the input values as date values, so I tried the following:
function CheckWeekNuber() {
var dateStr =SpreadsheetApp.getActiveSpreadsheet().getSheetByName("INSERT RAW DATA HERE").getRange(3,5,300,4).getValues();
var day = dateStr.substring(0,2);
var month = dateStr.substring(3,5);
var year = "20"+dateStr.substring(6,8);
var weekNumb = Utilities.formatDate(new Date(year, month-1, day), "GMT", "w");
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("WEEKNUMBERS").getRange(3,5,300,4).setValues(weekNumb);
}
It worked perfectly with a foor loop, converting each single value at a time. But it was super slow. My problem lays in using the ".substring()" formula for arrays, it does not seem to work..
Do you have any idea how to fix it?
The use of substring() is not possible when applying directly to an array. Looping the only way in getting the substring() of each element on an array.
Suggestion
If you are open to changing the data in your sheet, you can try using createTextFinder(".").replaceAllWithText("/") on your data range to convert your data to date format. Once you have this, you will still loop into your new data to get the week number of each date. Code is as follows and this is working on my end:
function CheckWeekNuber() {
var range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("INSERT RAW DATA HERE").getRange(3,5,300,4);
range.createTextFinder(".").replaceAllWith("/") // converts str date to date format
var dateFormat = range.getValues();
var lastRow = range.getLastRow();
var lastCol = range.getLastColumn();
var weekNumb = [];
for(var row in dateFormat){
for(var column in dateFormat[row]){
dateFormat[row][column] = Utilities.formatDate(new Date(dateFormat[row][column]), "GMT", "w");
}
}
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("WEEKNUMBERS").getRange(3,5,300,4).setValues(dateFormat);
}
First of all thanks in advance for helping, the community is great.
I have a problem parsing my date and time. Here is my code:
var date = mail.bodyText.match(/\=\= date \=\=\s*(.*[^\s*])/);
if (date) {
var string1 = date[1].match(/^\d{4}\-\d{2}-\d{2}/);
var string2 = date[2].match(\s(\d{2}\:\d{2}\:\d{2}));
var string3 = date[3].match(\s(\+\d{4}));
var parts1 = string1.split("-");
var parts2 = string2.split(":");
if (parts1 && parts2)
{
var dt = new Date(parseInt(parts1[0], 10), parseInt(parts1[1], 10) - 1, parseInt(parts1[2], 10), parseInt(parts2[3], 10), parseInt(parts2[4], 10), parseInt(parts2[5], 10));
}
date_final = dt;
}
date_final is defined elsewhere, and is in Date Time Picker format, and here is the input I am trying to parse:
blabla
== date ==
2016-02-13 16:22:10 +0200
blabla
Every time I execute the code, I get a parsing problem. The variable date_final cannot handle the parsed date. What do you think is missing from this code?
Update:
Here is what I'v etried out. Impossible for me to locate what's wrong:
var date = mail.bodyText.match(/\=\= date \=\=\s*(.*[^\s*])/);
if (date) {
var initial = date[1];
var formated = initial.substring(0, 19);
var final = formated.replace(/-/g, '/');
var last = new Date(final);
Field = last;
logging += "{date=" + Field + "}";
}
The code is actually parsing an email and sending the result over SSL. What surprises me the most is that the logs keep posting the following output of the date i naddition to the "parsing issue": date=Sat Feb 27 2016 16:22:10 GMT+0200 (CEST).
Do you think the problem comes from the code or could be related to how the appliance this code implemented on can handle it?
Thanks
Jane
Sorry for answering in comment.
Here's one solution to your question:
var dateStr = '2016-02-13 16:22:10 +0200';
// get yyyy-MM-dd HH:mm:ss
var formatedStr = dateStr.substring(0, 19);
// get yyyy/MM/dd HH:mm:ss in case of working on most of the browsers
var finalStr = formatedStr.replace(/-/g, '/');
// Date object can easily parse the datetime string we formated above
var date = new Date(finalStr);
Date object can parse complex strings.
Mail providers usually follow an RFC on how timestamps should be written, thus allowing other programming languages to heavily support it.
Just pass your string into date object and it will convert it for you.
let mailStr = `blabla
== date ==
2016-02-13 16:22:10 +0200
blabla`;
let regex = mailStr.match(/\=\= date \=\=\s*(.*[^\s*])/);
let dt = new Date(regex[1]);
console.log(dt);
The output is described in ISO-8601
Can I convert iso date to milliseconds?
for example I want to convert this iso
2012-02-10T13:19:11+0000
to milliseconds.
Because I want to compare current date from the created date. And created date is an iso date.
Try this
var date = new Date("11/21/1987 16:00:00"); // some mock date
var milliseconds = date.getTime();
// This will return you the number of milliseconds
// elapsed from January 1, 1970
// if your date is less than that date, the value will be negative
console.log(milliseconds);
EDIT
You've provided an ISO date. It is also accepted by the constructor of the Date object
var myDate = new Date("2012-02-10T13:19:11+0000");
var result = myDate.getTime();
console.log(result);
Edit
The best I've found is to get rid of the offset manually.
var myDate = new Date("2012-02-10T13:19:11+0000");
var offset = myDate.getTimezoneOffset() * 60 * 1000;
var withOffset = myDate.getTime();
var withoutOffset = withOffset - offset;
console.log(withOffset);
console.log(withoutOffset);
Seems working. As far as problems with converting ISO string into the Date object you may refer to the links provided.
EDIT
Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.
A shorthand of the previous solutions is
var myDate = +new Date("2012-02-10T13:19:11+0000");
It does an on the fly type conversion and directly outputs date in millisecond format.
Another way is also using parse method of Date util which only outputs EPOCH time in milliseconds.
var myDate = Date.parse("2012-02-10T13:19:11+0000");
Another option as of 2017 is to use Date.parse(). MDN's documentation points out, however, that it is unreliable prior to ES5.
var date = new Date(); // today's date and time in ISO format
var myDate = Date.parse(date);
See the fiddle for more details.
Yes, you can do this in a single line
let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673
Another possible solution is to compare current date with January 1, 1970, you can get January 1, 1970 by new Date(0);
var date = new Date();
var myDate= date - new Date(0);
Another solution could be to use Number object parser like this:
let result = Number(new Date("2012-02-10T13:19:11+0000"));
let resultWithGetTime = (new Date("2012-02-10T13:19:11+0000")).getTime();
console.log(result);
console.log(resultWithGetTime);
This converts to milliseconds just like getTime() on Date object
var date = new Date()
console.log(" Date in MS last three digit = "+ date.getMilliseconds())
console.log(" MS = "+ Date.now())
Using this we can get date in milliseconds
var date = new Date(date_string);
var milliseconds = date.getTime();
This worked for me!
if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);
In case if anyone wants to grab only the Time from a ISO Date, following will be helpful. I was searching for that and I couldn't find a question for it. So in case some one sees will be helpful.
let isoDate = '2020-09-28T15:27:15+05:30';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);
The output will be the only the time from isoDate which is,
15:27
I have a script that imports events from spreadsheets into calendar:
function caltest1() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 3; // Number of rows to process
var dataRange = sheet.getRange(startRow, 1, numRows, 5);
var data = dataRange.getValues();
var cal = CalendarApp.getDefaultCalendar();
for (i in data) {
var row = data[i];
var title = row[0]; // First column
var desc = row[1]; // Second column
var tstart = row[2];
var tstop = row[3];
var loc = row[4];
//cal.createEvent(title, new Date("March 3, 2010 08:00:00"), new Date("March 3, 2010 09:00:00"), {description:desc,location:loc});
cal.createEvent(title, tstart, tstop, {description:desc,location:loc});
}
}
The script works fine if my spreadsheet contains the data like:
Title Description Start Stop Channel
Mr Dear no drinks 5/6/2014 20:55:00 5/6/2014 21:57:00 what ever
But it does not work if I create my own date =CONCATENATE($D4, " ",$G4), given that D4 has a date and G4 has time combined into a single cell Date and time. I figured because it senses that concatenate creates a plain text and not a time formatting, but how can I fix it?
In spreadsheets, dates have a native value of an integer representing the number of days since december 31 1899 and time is a decimal value which is the fraction of a day ( 6 hours = 1/4 of a day for example , 0.25 day).
So when you add DATE+TIME (integer+decimal) in a spreadsheet you get a full date with time .
So the answer (as you noticed it in your comment on the other answer) is logically to ADD both values. That's actually the reason spreadsheets are build like that ! (to make it easy to use date and time)
Use the formula =D2+E2 in a new column and you get a complete date object directly useable in JavaScript.
In Javascript date and time are the same objects, there is no time object that has no date and no date without time : their native values are milliseconds counted from January 1 1970 at midnight (which is an integer).
Since the type of concatenated strings is text, you can convert them to date before calling the Calendar methods.
var tstart = new Date(row[2]);
var tstop = new Date(row[3]);
I successfully concatenated date and time by using
=text(A2,"dd/mm/yy") & ", " & text(B2,"HH:MM")
I concatenated date and time
I have the following data:
var currentTime: 2013-07-11 15:55:36+00:00
var currentTimezone: Africa/Asmera
I need a way to convert the currentTime in UTC to a new time based on currentTimezone.
I've looked into Timezone.js and I'm having trouble implementing it (the directions on the site are a little ambiguous)
The code for the function I'm intending on using is included. Thanks :)
<script>
$("#storeTime").click(function(){
storeCurrentTime();
})
$("#getTime").click(function(){
retrieveTime();
})
$("#storeTimezone").click(function(){
var yourTimezone = $('#timezone-select').find(":selected").text();
tz = yourTimezone.toString();
storeCurrentTimezone(tz);
})
$("#convertTime").click(function(){
//get the most recent UTC time, clean it up
var currentTime = $('#RetrievedTime').html();
currentTime = currentTime.split(": ")[1];
$('#convertedTime').html("Converted Time: " + currentTime);
//get the saved timezone
var currentTimezone = $('#storedTimezone').html();
})
</script>
You're going to need to know the timezone offset, so some sort of dictionary with strings to numbers.
// assuming your dictionary says 3 hours is the difference just for example.
var timezoneDiff = 3;
Then you can just make a new time like this
// Assuming you have the proper Date string format in your date field.
var currentDate = new Date(currentTime);
// Then just simply make a new date.
var newDate = new Date(currentDate.getTime() + 60 * 1000 * timezoneDiff);
Update
I've written a javascript helper for this which you can find at:
http://heuuuuth.com/projects/OlsonTZConverter.js
I pulled the timezone data from the wikipedia page https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Usage is as follows once included the script.
var offset = OlsonTZConverter.GetUTCOffset("Africa/Asmera");
or if there is Daylight Savings in effect:
var offset = OlsonTZConverter.GetUTCOffset("Africa/Asmera",true);
These will throw if you pass an invalid timezone, but you can check if a timezone is valid with:
var isValid = OlsonTZConverter.Contains("Africa/Asmera");
or just look at the entire dictionary with:
var tzDict = OlsonTZConverter.ListAllTimezones();
Hope this maybe saves someone some time sometime :).