Showing posts with label dates. Show all posts
Showing posts with label dates. Show all posts

1/28/2015

Google Docs: Replace Text / Date in Currently Selected Range of Cells: Google Spreadsheet Text to Columns Script

A Text to Columns function for Google's Spreadsheets 

This covers 2 topics:

  • Change non-standard text format to a date -- using a formula
  • Change an existing values in a Google Spreadsheet -- using a custom script.

Using a Google Sheet formula to convert YYYYMMDD to a standard date

I was downloading data from a Google Analytics Customized Report into a CSV file which I wanted to use in a Google Docs spreadsheet.

Example data:

DateSessionsPageviewsBounce RatePages / SessionNew Users
201501012,36112,7283.18%5.391,903
201501022,13712,8043.09%5.991,672
201501031,83312,8793.06%7.031,473
201501041,81612,8662.97%7.081,483

Delimiting the fixed width columns

As you can see, the first column has a genuine date in it, but it looks funky because it is not delimited. There is not slash or dash between the values of year, month and day.
I wanted to change YYYYMMDD into MM/DD/YYYY; and then change the resulting values to dates that the spreadsheet can work with. MS Excel can do this using a command called "Text to Columns"

I used this information from this page to create a formula that takes the fixed width value from a specified cell (in this case, A6), rearranges the order of the elements, and adds delimiters.

=DATEVALUE(Mid(A6,5,2) & "/" & Right(A6,2) & "/" & Left(A6,4))


Ex. Using this, "20150104" the function DATEVALUE converts the 8-character string or number into the U.S. date value "01/04/2014" (aka January 4, 2014).
But the problem is, the formula can't be entered into the original cell, right? The formula would replace the cell's value.


So, to see the correct value, you would have to place the formula into a different, blank cell. Perhaps, you might even create a new column to hold the value. Or, if you're like me, you want the new value to be in the same cell as the original value.


Using a Script to format all selected cells

Scripts can be used to add functionality to a document that doesn't already exist.

There's two parts to the process --

  1. Add an item to the menu bar, 
  2. Add a function that will execute when the menu item is selected.


As of January 2015, these are the steps to add the script:


  • Go to Tools > Script Editor...
An example or existing script will show up.
The onOpen function is where you insert the menu command.
The menu setup will contain a specific functionName to launch.
A second function is then created to invoke the specified functionName.
Here, we'll call the function name: convertDateYYYYMMDD.

The function first retrieves the values in the currently selected cells and saves them as an array called values.
A second blank array is created called newValues.
The script then loops through the current values and, if a value is not blank, it rearranges substrings taken from the date and inserts slashes between them. So, YYYYMMDD becomes MM/DD/YYYY.
Then it replaces the currently selected cell values with the new array.


  • To add the menu and functionality, paste this code into your Script Editor.


// ADDS MENU ITEM
function onOpen() {
  SpreadsheetApp.getActive().addMenu(
    'Convert', [{name:'Convert Date: YYYYMMDDD', functionName:'convertDateYYYYMMDD'}]);
}

// APPLY NEW DATE FORMAT TO SELECTED CELLS
function convertDateYYYYMMDD() {
   var values = SpreadsheetApp.getActiveRange().getValues();
 
   var newValues = new Array(); 
  for (i = 0; i < values.length; i++) {
    if (values[i][0] != '') {
      newValues.push(['=DATEVALUE(Mid(' + values[i][0] + ',5,2) & "/" & Right(' + values[i][0] + ',2) & "/" & Left(' + values[i][0] + ',4))']);
    } else {
      newValues.push(['']);
    }
  }
  SpreadsheetApp.getActiveRange().setValues(newValues);
}

  • When done, hit the Save button, and if this is new, name the project something meaningful to you.
  • You should see a new menu item: [Convert]. If not, you may need to save and reload your sheet.
  • If you see the menu item, first select the text you want to convert, then go to [Convert > Convert Date: YYYYMMDD].
  • The text may not look like what you were expecting. So, the final thing that you may need to do is to convert the selected cells to a date format. Go to:
Format > Number > Date

9/24/2009

Javascript: How to Get the Date, Month, Year and Weekday

Using the Date class
<script type="text/javascript">

// INSTANTIATE A DATE OBJECT
hereIsMyDate = new Date();

// EXTRACT THE PARTS OF THE CURRENT DATE
dayOfTheMonth = hereIsMyDate.getDate(); // RETURNS INTEGER 1-31

monthNumber = hereIsMyDate.getMonth(); // RETRUNS INTEGER 0-11 (for Jan-Dec)

weekdayNumber = hereIsMyDate.getDay(); // RETURNS INTEGER 0-6 (for Mon-Fri)

fullYear = hereIsMyDate.getFullYear(); // RETURNS 4-DIGIT YEAR (ex. 2010)

monthNamesArray = new Array("January","February","March","April","May","June","July","August","September","October","November","December");

monthName = monthNamesArray[monthNumber];

dayNamesArray = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday");

dayOfTheWeekName = dayNamesArray[weekdayNumber];

// EXAMPLE USAGE
document.write("<p>Today's date is " + dayOfTheWeekName + ", " + monthName + ", " + dayOfTheMonth + ", " + fullYear + "</p>");

document.write("<p>&copy; " + fullYear + " MyWebsiteName</p>");
</script>

Javascript has a set of functions built into the language that will give you information about dates.

The methods used to work with dates have been bundled together in something called a class. The class you will be using must be referred to by its pre-defined name. Conveniently for us, it is called: Date()



The first thing to do when using the Date class is to create something called an object. An object allows you to make a working version of the class. (You can't work with the Date() class directly.) You need to pick a name for this new object.

Here we'll call it: hereIsMyDate

To create this object (this copy of the Date() class), you write a statement like this:
hereIsMyDate = new Date();
Now, you can start using the functions or methods that come from the Date() class. There are many functions available including dates, times, and the ability to change dates and times. These functions should make for easy ways to go forward or backward in time and get information about that date. You could, for example, figure out what day of the week Valentine's Day will occur next year, what the time and date will be 8 hours from now, or perhaps get data about a date that occurred exactly 1035 days ago.




To get the current day of the month you use the .getFullYear() method: 
fullYear = hereIsMyDate.getFullYear();
To get the current day of the month you use the .getDate() method:
dayOfTheMonth = hereIsMyDate.getDate();
To get the  current day of the week, you use the .getDay() method. However, you will not get a string like "Monday" or "Mon," you will only get back an integer from 0 to 6, which represent Sunday to Saturday. To get a string you would have to create a separate array of date names and use the value sent back from the .getDay method to show a text version of the date:
dayOfTheWeekNumber = hereIsMyDate.getDay();

dayNamesArray = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");

dayOfTheWeekName = dayNamesArray[dayOfTheWeekNumber];

Similarly, to get the current month, you would use the .getMonth() method. The value returned will be from 0 to 11, representing January to December. If necessary, create an array of month names:
monthNumber = hereIsMyDate.getMonth();

monthNamesArray = new Array("January","February","March","April","May","June","July","August","September","October","November","December");

monthName = monthNamesArray[monthNumber];

Once you have your parts assigned to variables, you can create different uses for them. For example the code at the top of this document will output the following:


Today's date is Thursday, September, 24, 2009

© 2009 MyWebsiteName

For the most technical explanation of the Date() class and the way it works, please see Section 5.9 of the official JavaScript (a/k/a ECMAScript) specification ECMA-262.