SSブログ
前の10件 | -

Contact information [contact]

22Description-1.png

For illustrations of PinsPad, please refer to the destination of Link to App Support.
The url is following.
http://scheduledcontrollers.blog.so-net.ne.jp

The iTunes Preview of PinsPad is following URL.
https://itunes.apple.com/app/pinspad/id1207733310?mt=8


Use of a spreadsheet again

I have to reconsider the previous article, "Use of a spreadsheet".

[For Mac]
ManyTime app's data format is a tab-delimited text,
so you can create ManyTime data using the spreadsheet.
Also you can create it using the usual text editor.

It is simple to create data using the text editor, but it will take effort.
Here, I explain the method to create data using the spreadsheet.
For example, from cell A1, enter the following three events in a spreadsheet.

2015-12-18 17:00:00 2015-12-18 21:30:00 It is rain today.
2015-12-19 20:30:00 2015-12-19 22:30:00 It is also rain today.
2015-12-20 19:30:00 2015-12-20 23:00:00 Rain, but also sunny today.

The event in the line 1 is organized as follow:
Start time 2015-12-18 17:00:00
End time 2015-12-18 21:30:00
Comment It is rain today.

For entering the start time, select A1 cell, and enter '2015-12-18 17:00:00
in the formula bar.
For entering the end time, select B1 cell, and enter '2015-12-18 21:30:00
in the formula bar.
For entering the comment, select C1 cell, and enter "It is rain today."
in the formula bar.

The head character of start time string and end time string in the formula bar
will begin with a single quote.
Also the event in the line 2 is organized as follow:

For entering the start time, select A2 cell, and enter '2015-12-19 20:30:00
in the formula bar.
For entering the end time, select B2 cell, and enter '2015-12-19 22:30:00
in the formula bar.
For entering the comment, select C2 cell, and enter "It is also rain today."
in the formula bar.

Then the event in the line 3 is organized as follow:

For entering the start time, select A3 cell, and enter '2015-12-20 19:30:00
in the formula bar.
For entering the end time, select B3 cell, and enter '2015-12-20 23:00:00
in the formula bar.
For entering the comment, select C3 cell, and enter "Rain, but also sunny today."
in the formula bar.

Save the data named manytime-1.txt from the spreadsheet.
In this case, as the type of file, save by selecting the tab-delimited text.
If you are forced to save in csv extension, correct the file name to txt extension
after saving.

The file manytime-1.txt after editing looks like the following.
This data is for the course 1 of ManyTime app.
You can copy the contents to the existing manytime-1.txt file under
the Dropbox>Apps>manytime folder, or replace the the existing file.
If the existing manytime-1.txt is absent,place it in manytime folder.
Select the course 1 in ManyTime app and press the sync button in ManyTime app,
the data will be downloaded from Dropbox.

2015-12-18 17:00:00 2015-12-18 21:30:00 It is rain today.
2015-12-19 20:30:00 2015-12-19 22:30:00 It is also rain today.
2015-12-20 19:30:00 2015-12-20 23:00:00 Rain, but also sunny today.

Between the date and the time is a space.
Between the start date and the end date is a tab.
Between the end date and the comment is also a tab.


[For Windows]
After saving manytime-1.txt from the spreadsheet, read it using the text editor
with the text editor, and save again it with LF in UTF-8 without BOM. Use the
advanced text editor, such as EmEditor.

Note:
If the file name is manytime-2.txt in the manytime folder of Dropbox,
it will be the data for the course 2 in ManyTime app.
If manytime-3.txt, it will be for the course 3.
If manytime-4.txt, it will be for the course 4.

[ZAP]Service of making the data for ManyTime app from Google calendar part2

Post:2015-03-14
Update:2015-03-28,2015-04-28

Dropbox and Google Drive are storage services.
In Part 2, using Zapier that is another kind web service,
connect Dropbox with Google Drive.

Summary is as follows.

1: As the article of Part 1, by using the GAS script, you can set the
time-driven trigger event. As a result, data is appended to
Temp-manytime-4.txt file below Google Drive root.

2: Remove manytime-4.txt if the file exists in zapier folder.
Then you copy from Temp-manytime-4.txt file below Google Drive root,
and paste as "manytime-4.txt" in zapier folder of Google Drive.

Using GAS script that is invoked in the time-driven trigger event,
process of above 1 and above 2 is done in succession.

3: The trigger event occurs when a new manytime-4.txt file is created
in zapier folder of Google Drive. Then, Zap service that will copy
the file from Google Drive onto Dropbox is executed.


(A)Assumption
1: Joining in the Web service, Zapier
Zapier is a paid Web service that allows you to connect Web services
variety. Zapier has a trial period, and you can also select free plan.
This time, I assume that you can use the Web service Zap that will copy
from files of Google Drive onto Dropbox. On assume that Zapier is available,
I proceed with the following story.
Zapier's URL https://zapier.com

2: Creating the zapier folder below Google Drive root
Transferring a file to Dropbox, you can create the zapier folder below
 Google Drive.


(B)About GAS script
GAS script is almost same as part1. To perform the process of the above summary 2, the toDay function added the call of copyFileToFolder function. The script usage is the same as part1. Start the toDay function.

If manytime-4.txt exists in zapier folder, delete the file by copyFileToFolder function. Next, copy Temp-manytime-4.txt below Google Drive root, and then paste it as manytime-4.txt in zapier folder.


(C)Creation of Zap
After registering Zapier, you create the Zap service by logging into the Web site. When the trigger event of Google Drive creates the new file (manytime-4.txt) in zapier folder of Google Drive, this zap service will copy from the file in Google Drive, and then paste it in "Dropbox/Apps/manytime" folder.

Setting procedure of the Zap service is as follow:

Step 1: Choose a trigger and action
Select Google Drive, and select "New File in Folder" as Trigger.
(Source of copy.)

Select Dropbox, and select "Copy File from Trigger" as Action.
(Destination of copy.)

Step 2: Select a Google Drive account
Set the account of Google Drive.

Step 3: Select a Dropbox account
Set the account of Dropbox.

Step 4: Filter Google Drive triggers
Select zapier in Folder(option).

Step 5: Match up Google Drive File in Folder to Dropbox File from Trigger
- Select /Apps/manytime in Directory(required).
- Select File in File(required).
Pressing the right button (Insert GoogleDrive-icon fields), the menu
will be appeared under the text field. Select "File" item from the menu.
"File" icon will be appeared in the left side of the text field.
Specifying the file name is not required.
- Select yes in Overwrite(optional).
- Specify manytime-4 in Specify File Name(optional).
- Specify txt in Specify File Extension(optional).

Step 6: Test this Zap
After pressing the "Test Google Drive trigger" button, you will check
the manytime-4.txt file that is in /Apps/manytime folder of Dropbox.
You need to put manytime-4.txt in zapier folder of Google Drive.
The manytime-4.txt file has some test data.

Step 7: Name and turn this Zap on
Set CopyFromDriveToDropbox in Name this Zap.
(Change to the appropriate Zap name.)
Press the "Turn Zap on" button that will start the CopyFromDriveToDropbox
Zap service.


(D)Checking by ManyTime app
Select the course 4 in ManyTime app, press the sync button.


toDay.gs:
//By extracting the previous day's Google Calendar events and 
//exporting them to Google spreadsheet, you can create a data 
//for ManyTime app, and export it to Temp-manytime-4.txt file.
//Then, copy the file as manytime-4.txt to zapier under folder.
function toDay() {
  var start = new Date(); //本日 //Today
  start.setDate(start.getDate() - 1); //前日の日付を設定する //Set the start variable to the date of the previous day.
  var sheetName = Utilities.formatDate(start,"Asia/Tokyo", "yyyyMMdd");
  writeNewSheet(start, sheetName);
  //Since the time it takes to process sheet is created, wait 10 seconds.
  Utilities.sleep(10*1000);
  //The file name in zapier folder
  var csvFileName = 'manytime-4.txt';
  //The file name below Google Drive root
  var csvFileNameInRoot = 'Temp-manytime-4.txt';
  //Output file name of ManyTime data below Google Drive root.
  writeManyTimeFile(csvFileNameInRoot, sheetName);
  var folderName = "zapier";
  copyFileToFolder(folderName, csvFileName, csvFileNameInRoot);
}

//Write events in the date of the aStart argument to the sheet 
//with the name of the argument aSheetName.
//Hard-coded Calendar ID and Google Spreadsheet key.
function writeNewSheet(aStart, aSheetName){

  var ss = SpreadsheetApp.openById( 'Spreadsheet key' ), //5:Spreadsheet key of Google Spreadsheet
      sheet = ss.insertSheet(aSheetName),
      cals = ['Calendar ID'], c, cal, calName, //6:Calendar ID of Google Calendar
      events, i, details,
      eventslog = [], e,
      rows = [], range,
      anArray, startTime, eventTime,
      hourOffset, eventNumberInDay, aStartDay, previousStartDay,
      anEndDay;
  
  //If there is more than one calendar, each calendar becomes the target. 
  //Here calendar is one.
  for (c = 0; c < cals.length; c += 1) {

    cal = CalendarApp.getCalendarById(cals[c]);
    calName = cal.getTitle();
    //Get events in the date of the aStart argument.
    events = cal.getEventsForDay(aStart);
    Logger.log(events.length);
    events = events.reverse(); //Reverse order.

    //From the events variable, delete all-day events that are not 
    //in the date of the argument aStart . 
    anArray = new Array();
    startTime = Utilities.formatDate(aStart,"Asia/Tokyo", "yyyyMMdd");
    //Logger.log(startTime);
    for (i = 0; i < events.length; i++) {
      if (events[i].isAllDayEvent()) {
        eventTime = Utilities.formatDate(events[i].getStartTime(),"Asia/Tokyo", "yyyyMMdd");
        Logger.log(eventTime);
        //All-day events
        if (eventTime != startTime) {
          //The start date of all-day event is not the date of the argument aStart.
          continue;
        }
      }
      //Elements of the anArray variable are all-day events in the date of 
      //the argument aStart, or usual events in the date of the argument aStart.
      anArray.push(events[i]);
    }
    events = anArray;
    //Logger.log(events.length);
    //Add events in the current calendar to the array of all events.
    hourOffset = 0; //0時~23時 //8:Offset hours, 0 o'clock - 23 o'clock 
    eventNumberInDay = hourOffset - 1; //-1 + hourOffset
    eventslog = eventslog.concat(
      events.map(function(event) {
        if (event.isAllDayEvent()) {
          //All-day event
          aStartDay = Utilities.formatDate(event.getStartTime(),"Asia/Tokyo", "yyyyMMdd");
          if (aStartDay == previousStartDay) {
            eventNumberInDay = eventNumberInDay + 1;
          } else {
            eventNumberInDay = hourOffset; //0 + hourOffset
          }
          previousStartDay = aStartDay;
          //Calculation of the end time
          var milliSecStart = event.getStartTime().getTime();
          var newStartTime = new Date(milliSecStart + eventNumberInDay*3600*1000);
          var newEndTime = new Date(milliSecStart + (eventNumberInDay + 1)*3600*1000 - 60*1000);
          //Multi-day events support
          var milliSec = event.getEndTime().getTime();
          var anotherEndTime = new Date(milliSec - 60*1000); 
          anEndDay = Utilities.formatDate(anotherEndTime,"Asia/Tokyo", "yyyyMMdd");
          var endDateString = "";
          if (aStartDay != anEndDay) {
            //Put the ending date in a comment.
            endDateString = Utilities.formatDate(anotherEndTime,"Asia/Tokyo", "yyyy-MM-dd");
            endDateString = "(~" + endDateString + ")";
          }
          //
          return {
            time: new Date(event.getStartTime()).getTime(), // sort by this
            details: [
              Utilities.formatDate(newStartTime,"Asia/Tokyo", "yyyy-MM-dd HH:mm:ss@#"),
              Utilities.formatDate(newEndTime,"Asia/Tokyo", "yyyy-MM-dd HH:mm:ss@#"),
              event.getTitle() + endDateString,
              eventNumberInDay
            ]
          };
        } else {
          //Usually event
          var milliSec = event.getEndTime().getTime();
          var newEndTime = new Date(milliSec - 60*1000);
          return {
            time: new Date(event.getStartTime()).getTime(), // sort by this
            details: [
              Utilities.formatDate(event.getStartTime(),"Asia/Tokyo", "yyyy-MM-dd HH:mm:ss@#"),
              Utilities.formatDate(newEndTime,"Asia/Tokyo", "yyyy-MM-dd HH:mm:ss@#"),
              event.getTitle(),
              eventNumberInDay
            ]
          };
        }
      })
    );
  }
  // Sort array of event so date order can be either way by reversing a & b
  eventslog.sort(function(a, b) { return a.time - b.time; });

  rows = eventslog.map(function(entry) { return entry.details; });
  //If the number of rows is 0, it will be an error.
  if (rows.length > 0) {
    //range = sheet.getRange(1, 1, rows.length, 3);
    range = sheet.getRange(1, 1, rows.length, 4);
    range.setValues(rows);
  }
}

//Write ManyTime data to the file of the argument aCsvFileName from the sheet 
//with the name of the argument aSheetName.
function writeManyTimeFile(aCsvFileName, aSheetName) {

  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(aSheetName);
  var maxColumn = ss.getLastColumn() - 1;
  var maxRow    = ss.getLastRow();
  //If the sheet has no data, return from the function.
  if (maxColumn < 1 && (maxRow < 1)) {
    return;
  }
  //
  var data = ss.getRange(1,1,maxRow,maxColumn).getValues();
  var csvFile = "";
  //Create the content to export by extracting data from the sheet.
  if (data.length > 0) {
    var csv = "";
    for (var row = 0; row < data.length; row++) {
      for (var col = 0; col < data[row].length; col++) {

        //For example, remove the trailing @ from "2013-01-08 00:00:00 @". 
        //Logger.log(data[row][col].toString().indexOf("@#") != -1);
        if (data[row][col].toString().indexOf("@#") != -1) {
          data[row][col] = data[row][col].replace(/@#$/, "");
        }
      }
      csv += data[row].join("\t") + "\n";
    }
    csvFile = csv;
  }
  //Get the file of argument aCsvFileName
  /* 2015-04-25
  var files = DocsList.getAllFiles();
  var file;
  for (var i in files) {
    if (files[i].getName() == aCsvFileName) {
      file = files[i];
      break; 
    }
  }
  */
  var files = DriveApp.getFiles();
  var file = null;
  while (files.hasNext()) {
    file = files.next();
    if (file.getName() == aCsvFileName) {
      break;
    }
    file = null;
  }
  //The variable file if it exists, add lines of ManyTime data to the end as the existing file.
  //If it does not exist, create a new file with the contents of the aCsvFileName argument.
  if (file) {
    //file.append(csvFile); 2015-04-25
    var theContent = file.getAs('text/plain').getDataAsString();
    var resString = theContent.concat(csvFile);
    file.setContent(resString);
  } else {
    /* 2015-04-25
    var dataBlob;
    dataBlob = Utilities.newBlob(csvFile, 'text/plain', aCsvFileName);
    DocsList.createFile(dataBlob);
    */
    DriveApp.createFile(aCsvFileName, csvFile, 'text/plain');
  }
}


copyFileToFolder.gs:
//Copy the file that specified by aFileNameInRoot below Google Drive root.
//And paste the file that renamed to the aFileName variable
//under aFolderName folder. 
function copyFileToFolder(aFolderName, aFileName, aFileNameInRoot) {
  //var targetFolder = DocsList.getFolder(aFolderName); 2015-04-25
  var targetFolders = DriveApp.getFoldersByName(aFolderName);
  var targetFolder = targetFolders.next();
  //If there is the previous file under aFolderName folder (aFileName), delete it.
  var removeDoc = getFileByName(targetFolder, aFileName);
  if (removeDoc) {
    removeDoc.setTrashed(true);
  }
  //Copy the file that specified by aFileNameInRoot in Google Drive root. 
  //And paste the file that renamed to the aFileName variable under 
  //aFolderName folder.
  /* 2015-04-25
  var mainDoc = getFileByName(DocsList.getRootFolder(), aFileNameInRoot);
  mainDoc.makeCopy(aFileName).addToFolder(targetFolder);
  */
  var mainDoc = getFileByName(DriveApp.getRootFolder(), aFileNameInRoot);
  mainDoc.makeCopy(aFileName, targetFolder);
}

//Return the file that have the file name (specified by the filename argument) 
//under the folder (specified by the folder argument).
function getFileByName(folder, filename) {
  /* 2015-04-25
  var files = folder.find(filename);    
  for( var i in files){
    if ( files[i].getName() == filename ) 
    {
      Logger.log("found " + files[i].getName());
      return files[i];
    }
  } //for i in files
  */
  var file;
  var files = folder.getFilesByName(filename);
  while (files.hasNext()) {
    file = files.next();
    if (file.getName() == filename) {
      Logger.log("found " + file.getName());
      return file;
    }
  }
  //
  Logger.log("did not find " + filename);
} //getFileByName


getFileByName function is from the following article.
http://code.google.com/p/google-apps-script-issues/issues/detail?id=1127

[GAS]Service of making the data for ManyTime app from Google calendar part1

Post:2015-03-14
Update:2015-04-28

In this article, modifying the script of "[GAS]Creation of the data for ManyTime
app from Google calendar", you can create a Web service to get the events that
took place the day before and update the ManyTime app data everyday.

In Part 1, I will write about how to start the GAS script trigger in time.
In Part 2, I will write about how to copy the data of ManyTime app
from Google Drive to Dropbox via Zapier.

The program of this article will perform the following processing.

1:Extract the events in the previous day from Google Calendar, and writes to Google Spreadsheet.
2:By getting data from Google Spreadsheet above, write ManyTime data to
Google Drive.
3:The processing of the above 1 and 2 perform once a day in the time
that specified by the trigger function of Google Spreadsheets. In addition,
the triggering of the trigger time in this article will be once in
between 5:00 am and 6:00 am.


Summarizing the setting in accordance with this article, the input and output
is as follows:

Input: The yesterday event that you have entered before 5:00 am today in
Google Calendar.

Output: Yesterday events processing is performed between 5:00 am and
6:00 am on today, ManyTime app data based on Google Calendar events of
yesterday is appended to the Temp-manytime-4.txt below the Google Drive.


(A) About scripts
You create a document in Google Spreadsheet, and then set the script
below there. Because there are differences in the data that is entered
or your account, you may need to customize the script.

To customize the script, you will have to customize Calendar ID,
Spreadsheet key and etc.
The information necessary to customize is the same as the article
"[GAS]Creation of the data for ManyTime app from Google calendar",
please refer to the article.

The main customization points:

(1)Spreadsheet key of Google Spreadsheet
(2)Calendar ID of Google Calendar
(3)Waiting time - It is set to 10 seconds.
(4)Regional specification - Asia / Tokyo
(5)Newline character - settings \n, for Mac use.

Attentions:
1:As the day goes on, sheets in the spreadsheet will increase.
Delete unnecessary sheets.
2:ManyTime app data will be appended to the Temp-manytime-4.txt file.


(B)How to use
1:Create the document of Google Spreadsheet.
2:Open the script editor from "Tools>Script editor...".
3:Select "File>New>Script file", and create a new script.
4:Paste the code below toDay.gs and save the script.
5:Select toDay from "Select function" pull-down menu.
6:Press the Run button. Accept the warning dialog at run time depending on
your circumstances.
7:Make sure the contents of Temp-manytime-4.txt on Google Drive.

8:Select Resources>"Current project's triggers" in Script editor.
9:Save the setting of the trigger to start the script toDay.
10:Before the script is run, enter events of the day before to
Google Calendar.


(C)Time trigger settings
1:Select Resources>"Current project's triggers" in Script editor.
2:Press the "Add a new trigger" link in the invoked dialog box.
3:Select "toDay" as "Run" in the dialog box.
4:Select "Time-driven" as "Events" in the dialog box.
5:Select "Day timer" in the dialog box.
6:Set the execution time in the dialog box.
For example, you set "5am to 6am".
"toDay" function will run somewhere in between 5:00 am and 6:00 am.
7:Press Save button in the dialog box.

The "the day before" phrase have used many times in this article,
but you can change it in "the day" or "the next day" by editing the script.


toDay.gs:
//Extract Google Calendar events of the day before, 
//you can create ManyTime data into Google Spreadsheet, and 
//export it to Temp-manytime-4.txt file.
function toDay() {
  var start = new Date(); //The start date is today.
  start.setDate(start.getDate() - 1); //Change start date to the day before.
  //(4)Regional specification - Asia / Tokyo
  var sheetName = Utilities.formatDate(start,"Asia/Tokyo", "yyyyMMdd");
  writeNewSheet(start, sheetName);
  //(3)Waiting time - It is set to 10 seconds.
  Utilities.sleep(10*1000);
  //var csvFileName = 'manytime-4.txt';
  var csvFileNameInRoot = 'Temp-manytime-4.txt'; //Output file name of ManyTime data.
  writeManyTimeFile(csvFileNameInRoot, sheetName);
  //var folderName = "zapier";
  //copyFileToFolder(folderName, csvFileName, csvFileNameInRoot);
}

//Write events of aStart(argument) to the sheet named aSheetName( argument ).
//Hardcode Calendar ID and Google Spreadsheet key.
function writeNewSheet(aStart, aSheetName){

  var ss = SpreadsheetApp.openById( 'Spreadsheet key' ), //(1)Spreadsheet key of Google Spreadsheet
      sheet = ss.insertSheet(aSheetName),
      cals = ['Calendar ID'], c, cal, calName, //(2)Calendar ID of Google Calendar
      events, i, details,
      eventslog = [], e,
      rows = [], range,
      anArray, startTime, eventTime,
      hourOffset, eventNumberInDay, aStartDay, previousStartDay,
      anEndDay;

  //Each becomes the target if there is more than one calendar. 
  //The calendar only one here.
  for (c = 0; c < cals.length; c += 1) {

    cal = CalendarApp.getCalendarById(cals[c]);
    calName = cal.getTitle();
    //Get the aStart Event.
    events = cal.getEventsForDay(aStart);
    Logger.log(events.length);
    events = events.reverse(); //Reverse order.
    
    //Eliminate the all-day events that are not in the same day as the aStart
    //from events.
    anArray = new Array();
    //(4)Regional specification - Asia / Tokyo
    startTime = Utilities.formatDate(aStart,"Asia/Tokyo", "yyyyMMdd");
    Logger.log(startTime);
    for (i = 0; i < events.length; i++) {
      if (events[i].isAllDayEvent()) {
        //Get the start date of the event.(4)Regional specification - Asia / Tokyo
        eventTime = Utilities.formatDate(events[i].getStartTime(),"Asia/Tokyo", "yyyyMMdd");
        //Logger.log(eventTime);
        //All-day events
        if (eventTime != startTime) {
          //The start date of all-day event is not the argument aStart.
          continue;
        }
      }
      //It is all-day events of aStart, or usual events of aStart.
      anArray.push(events[i]);
    }
    events = anArray;
    //Logger.log(events.length);
    //From events, eliminate all-day events of the argument anEnd later.
    hourOffset = 0; //Offset hours, 0 o'clock - 23 o'clock 
    eventNumberInDay = hourOffset - 1; //-1 + hourOffset
    eventslog = eventslog.concat(
      events.map(function(event) {
        if (event.isAllDayEvent()) {
          //All-day event (4)Regional specification - Asia / Tokyo
          aStartDay = Utilities.formatDate(event.getStartTime(),"Asia/Tokyo", "yyyyMMdd");
          if (aStartDay == previousStartDay) {
            eventNumberInDay = eventNumberInDay + 1;
          } else {
            eventNumberInDay = hourOffset; //0 + hourOffset
          }
          previousStartDay = aStartDay;
          //Calculation of the end time
          var milliSecStart = event.getStartTime().getTime();
          var newStartTime = new Date(milliSecStart + eventNumberInDay*3600*1000);
          var newEndTime = new Date(milliSecStart + (eventNumberInDay + 1)*3600*1000 - 60*1000);
          //Multi-day events support
          var milliSec = event.getEndTime().getTime();
          var anotherEndTime = new Date(milliSec – 60*1000);
          //(4)Regional specification - Asia / Tokyo
          anEndDay = Utilities.formatDate(anotherEndTime,"Asia/Tokyo", "yyyyMMdd");
          var endDateString = "";
          if (aStartDay != anEndDay) {
            //Write "end date" in a comment.(4)Regional specification - Asia / Tokyo
            endDateString = Utilities.formatDate(anotherEndTime,"Asia/Tokyo", "yyyy-MM-dd");
            endDateString = "(~" + endDateString + ")";
          }
          //
          return {
            time: new Date(event.getStartTime()).getTime(), // sort by this
            details: [
            //(4)Regional specification - Asia / Tokyo
              Utilities.formatDate(newStartTime,"Asia/Tokyo", "yyyy-MM-dd HH:mm:ss@#"),
              Utilities.formatDate(newEndTime,"Asia/Tokyo", "yyyy-MM-dd HH:mm:ss@#"),
              event.getTitle() + endDateString,
              eventNumberInDay
            ]
          };
        } else {
          //Usually event
          var milliSec = event.getEndTime().getTime();
          var newEndTime = new Date(milliSec - 60*1000);
          return {
            time: new Date(event.getStartTime()).getTime(), // sort by this
            details: [
              //(4)Regional specification - Asia / Tokyo
              Utilities.formatDate(event.getStartTime(),"Asia/Tokyo", "yyyy-MM-dd HH:mm:ss@#"),
              Utilities.formatDate(newEndTime,"Asia/Tokyo", "yyyy-MM-dd HH:mm:ss@#"),
              event.getTitle(),
              eventNumberInDay
            ]
          };
        }
      })
    );
  }
  // Sort array of event so date order can be either way by reversing a & b
  eventslog.sort(function(a, b) { return a.time - b.time; });

  rows = eventslog.map(function(entry) { return entry.details; });
  //If the number of rows is 0, it will be an error.
  if (rows.length > 0) {
    //range = sheet.getRange(1, 1, rows.length, 3);
    range = sheet.getRange(1, 1, rows.length, 4);
    range.setValues(rows);
  }
}

//Write ManyTime data to the file argument aCsvFileName from the sheet 
//with the name of the argument aSheetName.
function writeManyTimeFile(aCsvFileName, aSheetName) {

  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(aSheetName);
  var maxColumn = ss.getLastColumn() - 1;
  var maxRow    = ss.getLastRow();
  //If the sheet has no data, return from the function.
  if (maxColumn < 1 && (maxRow < 1)) {
    return;
  }
  //
  var data = ss.getRange(1,1,maxRow,maxColumn).getValues();
  var csvFile = "";
  //Create the content for exporting that extracts data from the sheet.
  if (data.length > 0) {
    var csv = "";
    for (var row = 0; row < data.length; row++) {
      for (var col = 0; col < data[row].length; col++) {
        //For example, remove the trailing @ from "2013-01-08 00:00:00 @". 
        //Logger.log(data[row][col].toString().indexOf("@#") != -1);
        if (data[row][col].toString().indexOf("@#") != -1) {
          data[row][col] = data[row][col].replace(/@#$/, "");
        }
      }
      //(5)Newline character - settings \n, for Mac use.
      csv += data[row].join("\t") + "\n";
    }
    csvFile = csv;
  }
  //Get the file of argument aCsvFileName
  /* 2015-04-25
  var files = DocsList.getAllFiles();
  var file;
  for (var i in files) {
    if (files[i].getName() == aCsvFileName) {
      file = files[i];
      break; 
    }
  }
  */
  var files = DriveApp.getFiles();
  var file = null;
  while (files.hasNext()) {
    file = files.next();
    if (file.getName() == aCsvFileName) {
      break;
    }
    file = null;
  }
  //The variable file if it exists, add lines of ManyTime data to 
  //the end of the existing file.
  //If it does not exist, create a new file with the name of the aCsvFileName argument.
  if (file) {
    //file.append(csvFile); 2015-04-25
    var theContent = file.getAs('text/plain').getDataAsString();
    var resString = theContent.concat(csvFile);
    file.setContent(resString);
  } else {
    /* 2015-04-25
    var dataBlob;
    dataBlob = Utilities.newBlob(csvFile, 'text/plain', aCsvFileName);
    DocsList.createFile(dataBlob);
    */
    DriveApp.createFile(aCsvFileName, csvFile, 'text/plain');
  }
}

Creating KML data by converting ManyTime app data

On Mac, this ruby script translates ManyTime data to KML data.

This ruby script performs and translates the manytime-2.txt file
to the output.txt file. It works in the terminal on Mac OS X 10.8.5.
The Ruby 1.8.7 is used.

$ ruby convertKML.rb manytime-2.txt > output.kml

manytime-2.txt:
2013-12-05 21:18:00 2013-12-05 21:23:00  [2013-12-05 21:20:51,34.985458,135.757755]
2013-12-05 22:25:00 2013-12-05 22:30:00  [2013-12-05 22:25:56,35.039370,135.729243]


output.txt:




  2013-12-05 21:20:51
  
  135.757755,34.985458,undefined


  2013-12-05 22:25:56
  
  135.729243,35.039370,undefined





convertKML.rb:
#From the argument aString that is the result of the pattern match, 
#create a  row to output.
def nameString(aMatchString)
  withoutParentheses = aMatchString.sub(/\[/,"")
  withoutParentheses = withoutParentheses.sub(/\]/,"")
  anArray = withoutParentheses.split(",")
  return "#{anArray[0]}"
end

#From the argument previousString that is a string in front of the pattern match result, 
#create a  row to output.
def descriptionString(previousMatchString)
  return ""
end

#From the argument aCoordinates that is an array of coordinate value data, 
#create a  row to output. Height data does not exist, so output "undefined".
def pointString(aCoordinates)
  #In  row, it is output in the form  longitude, latitude, height .
  return "#{aCoordinates[7]},#{aCoordinates[6]},undefined"
end

#From the argument aCoordinates that is an array of coordinates values, 
#create a string of the coordinates value.
def coordinatesString(aCoordinates)
  #For example, it returns the string form of "2013-11-21 18:35:46,34.555555,135.777777".
  date = "#{aCoordinates[0]}-#{aCoordinates[1]}-#{aCoordinates[2]}"
  time = "#{aCoordinates[3]}:#{aCoordinates[4]}:#{aCoordinates[5]}"
  coordinates = "#{aCoordinates[6]},#{aCoordinates[7]}"
  return "#{date} #{time},#{coordinates}"
end

aHash = Hash.new
File.open(ARGV[0], "r") {
  | f |
  puts ""
  puts ""
  puts ""
  while line = f.gets
    #Create an array with coordinate values ​​that match the regular expression. 
    #Specify the pattern, for example, to match "2013-11-21 18:35:46,34.555555,135.777777".
    coordinatesArray = line.scan(/\[([1]{1}[9]{1}[9]{1}\d{1}|[2-9]{1}\d{3})-([0,1]?\d{1})-([0-2]?\d{1}|[3][0,1]{1})\s([0]?\d|1\d|2[0-3]):([0-5]\d):([0-5]\d),(\-?\d{1,2}\.\d{6}),(\-?\d{1,3}\.\d{6})\]/)
    #If there is a matched coordinates value in the line, perform text output process.
    if (coordinatesArray.length > 0)
      #Get the last coordinates value ​​from the results of the scan.
      lastCoordinates = coordinatesArray.last
      #Get a string of coordinates value ​​from an array of coordinates values.
      aCoordinatesString = coordinatesString(lastCoordinates)
      #Create the condition of pattern matching.
      aMatch = "\\[" + aCoordinatesString + "\\]"
      #Pattern-match the last coordinates value in the line.
      /#{aMatch}/ =~ line
      puts ""
      puts "  #{nameString($&)}"
      puts "  #{descriptionString($`)}"
      puts "  #{pointString(lastCoordinates)}"
      puts ""
    end
  end
  puts ""
  puts ""
}


[GAS]Creation of the data for ManyTime app from Google calendar

In this article, you can make the following process by using Google Apps Script.

1:Extract the events in a given period from Google Calendar, write to Google
Spreadsheet.
2:By getting data from Google Spreadsheet above, write ManyTime data to
Google Drive.

(A) About scripts
You can create a document in Google Spreadsheet, and then set the script
below there. Because there are differences in the data that is entered
or your account, you may need to customize the script. I write the following
additional information.

The main customization point:

fromDayToDay
1:The start date of the period specified
2:The end date of the period specified
3:Waiting time - It is set to 10 seconds.
4:Output file name of ManyTime data.

writeNewSheetFromToOn
5:Spreadsheet key of Google Spreadsheet
6:Calendar ID of Google Calendar
7:Regional specification - Asia / Tokyo
8:Offset hours

writeManyTimeFileFromTo
9:Newline character - settings \n, for Mac use.


2:The end date of the period specified
In the script, the end variable is a Date object that has the period specified end
date. For example, if the end variable is the Date object of '2013/12/11',
the end time of the period specified will be '2013-12-10 23:59:59' before
'2013-12-11 00:00:00'.
If you want to get events between 12/09 and 12/10, specify that the start day is
'2013/12/09' and the end day is '2013/12/11'.

5:How to get the spreadsheet key of Google Spreadsheet:
Open the Google Spreadsheet document that you created in Google Drive,and
make sure the URL. Although it is a URL like
https://docs.google.com/spreadsheet/ccc?key=...&usp = ...,
in this, the subsequent part of 'key=' is the spreadsheet key.

6:How to get Calendar ID of Google Calendar:
In 'My calendars' at the left of Google Calendar, ex. in 'Working',
select 'Calendar Settings' item from the arrow button menu of the calendar
that you want to. Get Calendar ID from Calendar Address of 'Working' Details
after opening the page. The script below uses only one calendar.

7:Regional specification - Asia/Tokyo
If you does not live in Asia/Tokyo region,
select "File>New>Script file" in Script editor, and create a new script as
following.
  function logTimeZone() {
    var timeZone = Session.getTimeZone();
    Logger.log(timeZone);
  }

Then, run the script, select "View>Logs" and check the dialog.

https://developers.google.com/apps-script/reference/base/session

8:hourOffset veriable
In the script below, all-day events have the length of one hour.
The hourOffset specifies the start time of the first all-day event.
It will be 0:00:00 if you specify 0, and it will be 13:00:00 if you specify 13.
For example, as there are all-day event #1 and all-day event #2,
if you specify the hourOffset to 0, event #1 will be between 00:00:00
and 00:59:00, and event #2 will be between 01:00:00 and 01:59:00.

Events of Google Calendar:
Google Calendar events to be handled, these are assumed events with
no overlap in time.
All-day events are one hour long, they will sort in the order after
the hourOffset.
It should be noted, can not be handled in ManyTime when normal events
and all-day events overlap.
Multi-day events will be all-day events that have the start date in the period.
Multi-day events do not handle if the start date is not included in the period.

Code that was helpful in the script:
http://stackoverflow.com/questions/14415752/google-calendar-app-script
http://micomura.hatenablog.jp/entry/2012/01/30/180803
http://d4-1977.hatenablog.com/entry/20110116/1295140259

(B)How to use
1:Create the document of Google Spreadsheet.
2:Open the script editor from "Tools>Script editor...".
3:Select "File>New>Script file", and create a new script.
4:Paste the code below fromDaytoDay.gs to replace the script.
5:Select fromDaytoDay from "Select function" menu.
6:Press the Run button. Accept the warning dialog at run time depending on
your circumstances.
7:Make sure the contents of manytime-4.txt on Google Drive.
8:Copy the contents of manytime-4.txt file to Dropbox, and make sure the data
with ManyTime app.
9:Delete the sheet that is generated by the script as necessary.

fromDayToDay.gs:
//Extract Google Calendar events of the specified period, 
//you can create ManyTime data into Google Spreadsheet, and 
//export it to manytime-4.txt file.

function fromDayToDay() {
  var start = new Date('2013/12/09'); //1:The start date of the period specified
  var end = new Date( '2013/12/11' ); //2:The end date of the period specified
  var sheetName = Utilities.formatDate(start,"Asia/Tokyo", "yyyy-MM-dd"); //7:Regional specification
  writeNewSheetFromToOn(start, end, sheetName);
  //3:Waiting time - It is set to 10 seconds.
  Utilities.sleep(10*1000);
  var csvFileName = 'manytime-4.txt'; //4:Output file name of ManyTime data.
  writeManyTimeFileFromTo(sheetName, csvFileName);
}

//Write to the sheet with the name of the argument aSheetName, the events between 
//the aStart arguments and anEnd.
//Hard-coded Calendar ID and Google Spreadsheet key.

function writeNewSheetFromToOn(aStart, anEnd, aSheetName){

  var ss = SpreadsheetApp.openById( 'Spreadsheet key' ), //5:Spreadsheet key of Google Spreadsheet
      sheet = ss.insertSheet(aSheetName),
      cals = ['Calendar ID'], c, cal, calName, //6:Calendar ID of Google Calendar
      events, i, details,
      eventslog = [], e,
      rows = [], range,
      anArray, startTime, eventTime, endTime,
      hourOffset, eventNumberInDay, aStartDay, previousStartDay,
      anEndDay, aRegionalSpec = "Asia/Tokyo"; //7:Regional specification

  //Each to be eligible if you have more than one calendar. The only one here.
  for (c = 0; c < cals.length; c += 1) {

    cal = CalendarApp.getCalendarById(cals[c]);
    calName = cal.getTitle();
    //Get the events between aStart and anEnd.
    events = cal.getEvents(aStart, anEnd);
    events = events.reverse(); //Reverse order.
    
    //From events, eliminate all-day events of the previous argument aStart.
    anArray = new Array();
    startTime = Utilities.formatDate(aStart,aRegionalSpec, "yyyyMMdd");
    for (i = 0; i < events.length; i++) {
      if (events[i].isAllDayEvent()) {
        eventTime = Utilities.formatDate(events[i].getStartTime(),aRegionalSpec, "yyyyMMdd");
        //All-day events
        if (eventTime < startTime) {
          //The start date of all-day event is before the start date of the argument aStart.
          continue;
        }
      }
      //It is all-day event of argument aStart later, or usual events of aStart later.
      anArray.push(events[i]);
    }
    events = anArray;
    //From events, eliminate all-day events of the argument anEnd later.
    anArray = new Array();
    //Get the start date of the argument anEnd.
    endTime = Utilities.formatDate(anEnd,aRegionalSpec, "yyyyMMdd");
    for (i = 0; i < events.length; i++) {
      if (events[i].isAllDayEvent()) {
        //Get the start date of the event.
        eventTime = Utilities.formatDate(events[i].getStartTime(),aRegionalSpec, "yyyyMMdd");
        //All-day events
        if (endTime <= eventTime) {
          //Start date of all-day event is the argument anEnd later.
          continue;
        }
      }
      //All-day events of the previous days of anEnd, 
      //or usually events of the previous day of anEnd.
      anArray.push(events[i]);
    }
    //Processing of events
    events = anArray;
    
    //Add events of the current calendar to the array of all events.
    hourOffset = 0; //8:Offset hours, 0 o'clock - 23 o'clock 
    eventNumberInDay = hourOffset - 1; //-1 + hourOffset
    eventslog = eventslog.concat(
      events.map(function(event) {
        if (event.isAllDayEvent()) {
          //All-day event
          aStartDay = Utilities.formatDate(event.getStartTime(),aRegionalSpec, "yyyyMMdd");
          if (aStartDay == previousStartDay) {
            eventNumberInDay = eventNumberInDay + 1;
          } else {
            eventNumberInDay = hourOffset; //0 + hourOffset
          }
          previousStartDay = aStartDay;
          //Calculation of the end time
          var milliSecStart = event.getStartTime().getTime();
          var newStartTime = new Date(milliSecStart + eventNumberInDay*3600*1000);
          var newEndTime = new Date(milliSecStart + (eventNumberInDay + 1)*3600*1000 - 60*1000);
          //Multi-day events support
          var milliSec = event.getEndTime().getTime();
          var anotherEndTime = new Date(milliSec - 60*1000);
          anEndDay = Utilities.formatDate(anotherEndTime,aRegionalSpec, "yyyyMMdd"); 
          var endDateString = "";
          if (aStartDay != anEndDay) {
            //Put the ending date in a comment.
            endDateString = Utilities.formatDate(anotherEndTime,aRegionalSpec, "yyyy-MM-dd"); 
            endDateString = "(~" + endDateString + ")";
          }
          //
          return {
            time: new Date(event.getStartTime()).getTime(), // sort by this
            details: [
              Utilities.formatDate(newStartTime,aRegionalSpec, "yyyy-MM-dd HH:mm:ss@"),
              Utilities.formatDate(newEndTime,aRegionalSpec, "yyyy-MM-dd HH:mm:ss@"),
              event.getTitle() + endDateString,
              eventNumberInDay
            ]
          };
        } else {
          //Usually event
          var milliSec = event.getEndTime().getTime();
          var newEndTime = new Date(milliSec - 60*1000);
          return {
            time: new Date(event.getStartTime()).getTime(), // sort by this
            details: [
              Utilities.formatDate(event.getStartTime(),aRegionalSpec, "yyyy-MM-dd HH:mm:ss@"),
              Utilities.formatDate(newEndTime,aRegionalSpec, "yyyy-MM-dd HH:mm:ss@"),
              event.getTitle(),
              eventNumberInDay
            ]
          };
        }
      })
    );
  }

  // Sort array of event so date order can be either way by reversing a & b
  eventslog.sort(function(a, b) { return a.time - b.time; });

  rows = eventslog.map(function(entry) { return entry.details; });
  //If thhe number of rows is 0, it will be an error.
  if (rows.length > 0) {
    range = sheet.getRange(1, 1, rows.length, 4);
    range.setValues(rows);
  }
}

//Write ManyTime data to the file argument aCsvFileName from the sheet 
//with the name of the argument aSheetName.
function writeManyTimeFileFromTo(aSheetName, aCsvFileName) {

  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(aSheetName);
  var maxColumn = ss.getLastColumn() - 1; //Correction: copy 3 columns from 4 columns.
  var maxRow    = ss.getLastRow();
  //If the sheet has no data, return from the function.
  if (maxColumn < 1 && (maxRow < 1)) {
    return;
  }
  //
  var data = ss.getRange(1,1,maxRow,maxColumn).getValues();
  var csvFile = "";
  //Create a content export to extract data from the sheet.
  if (data.length > 0) {
    var csv = "";
    for (var row = 0; row < data.length; row++) {
      for (var col = 0; col < data[row].length; col++) {
          //For example, remove the trailing @ from "2013-01-08 00:00:00 @". 
        if (data[row][col].toString().indexOf("@") != -1) {
          data[row][col] = data[row][col].replace(/@/, "");
        }
      }

      csv += data[row].join("\t") + "\n"; //9:Newline character
    }
    csvFile = csv;
  }
  //Get the file of argument aCsvFileName
  var files = DocsList.getAllFiles();
  var file;
  for (var i in files) {
    if (files[i].getName() == aCsvFileName) {
      file = files[i];
      break; 
    }
  }
  //The variable file if it exists, add lines of ManyTime data to the end as the existing file.
  //If it does not exist, create a new file with the contents of the aCsvFileName argument.
  if (file) {
    file.append(csvFile);
  } else {
    var dataBlob;
    dataBlob = Utilities.newBlob(csvFile, 'text/plain', aCsvFileName);
    DocsList.createFile(dataBlob);
  }
}


Sample data

By the data of ManyTime, the tab (\t) is used as a separator.
On Web screen, since the tab cannot be displayed, in order to offer the sample
data of ManyTime, GitHub is used.

Contents of manytimetips-master/english:
a:Creation of a garbage collection calendar
manytime-1.txt
b:Data format
manytime-1.txt (2013 october)
c:Time difference conversion
input-ja.txt

Download to your Mac or PC from GitHub site. File is in the zip format.
The URL is as follows:
https://github.com/manytime777/manytimetips

The file to download:
manytimetips-master.zip

Time difference conversion II

post:2013-09-05
update:2014-01-16

Let's consider time difference conversion, again.

Suppose that there is the following data.
This data is a timetable used in U.S., odd lines are time of onset and
even lines are termination time.
This time zone is Pacific Standard Time (PST) .
Although there is no comment data in this data, it becomes two events
in ManyTime data.

input-1.txt:
06 03, 2013 7:15 AM
06 03, 2013 8:10 PM
06 05, 2013 6:12 PM
06 07, 2013 1:08 AM

Notes:Finally a new-line is required.

This data can be changed into ManyTime data of the
Japan Standard Time (JST) 17 hours after PST by
the shell script.

The shell script is performed and translates input-1.txt to
the output. It works in the terminal on Mac OS X 10.8.4.
The date command attached to Mac is used for conversion of
the time difference in the shell script. This is the date
command of BSD system and options differ from SystemV system.

$ chmod u+x conv_pst+17.sh
$ ./conv_pst+17.sh input-1.txt

output:
2013-06-04 00:15:00\t2013-06-04 13:10:00
2013-06-06 11:12:00\t2013-06-07 18:08:00

Notes:\t is a tab character.

conv_pst+17.sh:
#!/bin/sh
isodd="1"
while read line;
do
	if [ "$isodd" = "1" ];
	then
		isodd="0"
		a=$(date -v+17H -j -f "%m %d, %Y %H:%M %p" "$line" "+%Y-%m-%d %H:%M:00")
	else
		isodd="1"
		b=$(date -v+17H -j -f "%m %d, %Y %H:%M %p" "$line" "+%Y-%m-%d %H:%M:00")
		printf "%s\t" "$a"
		printf "%s\n" "$b"
	fi
done < $1



The following is a Windows PowerShell version 3.0 script.
After storage in the default character code of Windows, use the PS script.
In my japanese environment of Windows7 SP1, character code is Shift JIS and
new line is \r\n. Input-1.txt is also Shift JIS and new line is \r\n.
Convert to the appropriate character code in English environment.

PS > .\conv_pst+17d.ps1 input-1.txt

conv_pst+17d.ps1:
#Read the file of two rows data set with "MM dd, yyyy h:mm tt" format.
#Be converted to the shifted data after 17 hours.

#Creating the input file path
$filepath = Split-Path $MyInvocation.MyCommand.Path
$inputFilePath = Join-Path $filepath $args[0]

#Get the input file contents
$inRecords = Get-Content $inputFilePath

# The body of the script
$isodd = 1
#Set to 17 hours after
$offsetHours = 17
$strStartTime = ""
$strEndTime = ""
foreach($inRecord in $inRecords)
{
    if ($isodd -eq 1) {
        $isodd = 0
        #String start time of local time.
        $strStartTime = $inRecord
        #Conversion to the start time from string start time.
        $startTime = [datetime]::ParseExact($strStartTime,"MM dd, yyyy h:mm tt", [System.Globalization.CultureInfo]::CreateSpecificCulture("en-US"))
        #Add 17 hours to the start time.
        $startTime = $startTime.AddHours($offsetHours)
        #Conversion to the string start time from the start time is added for 17 hours.
        $strStartTime = $startTime.ToString("yyyy-MM-dd HH:mm:ss")
    }
    else {
        $isodd = 1
        #String end time of local time.
        $strEndTime = $inRecord
        #Conversion to the end time from end time string.
        $endTime = [datetime]::ParseExact($strEndTime,"MM dd, yyyy h:mm tt", [System.Globalization.CultureInfo]::CreateSpecificCulture("en-US"))
        #Add 17 hours to the end time.
        $endTime = $endTime.AddHours($offsetHours)
        #Conversion to the string end time from the end time is added for 17 hours.
        $strEndTime = $endTime.ToString("yyyy-MM-dd HH:mm:ss")
        #Output
        $newLine = $strStartTime + "`t" + $strEndTime
        $newLine
    }
}

Time difference conversion

post:2013-09-05
update:2014-01-15

Let's consider time difference conversion.
Suppose that there is the following ManyTime data.
This time zone is Japan Standard Time (JST).

input-ja.txt:
2013-01-04 00:15:00\t2013-01-04 13:10:00\tComment1
2013-01-06 11:12:00\t2013-01-07 18:08:00\tComment2

Notes:\t is a tab character. Finally a new-line is required.

This data can be changed into ManyTime data of the
Pacific Standard Time (PST) 17 hours before JST by
the shell script.

The shell script is performed and translates input-ja.txt to
the output. It works in the terminal on Mac OS X 10.8.4.
The date command attached to Mac is used for conversion of
the time difference in the shell script. This is the date
command of BSD system and options differ from SystemV system.

$ chmod u+x conv_jst-17.sh
$ ./conv_jst-17.sh input-ja.txt

output:
2013-01-04 00:15:00\t2013-01-04 13:10:00\tComment1
2013-01-06 11:12:00\t2013-01-07 18:08:00\tComment2

2013-01-03 07:15:00\t2013-01-03 20:10:00\tComment1
2013-01-05 18:12:00\t2013-01-07 01:08:00\tComment2

conv_jst-17.sh:
#!/bin/sh

cat $1
printf "\n"

while read line;
do
	st=`echo "$line" | cut -f1`
	et=`echo "$line" | cut -f2`
	cm=`echo "$line" | cut -f3`
	a=$(date -v-17H -j -f "%Y-%m-%d %H:%M:%S" "$st" "+%Y-%m-%d %H:%M:00")
	b=$(date -v-17H -j -f "%Y-%m-%d %H:%M:%S" "$et" "+%Y-%m-%d %H:%M:00")
	printf "%s\t" "$a"
	printf "%s\t" "$b"
	printf "%s\n" "$cm"
done < $1



The following is a Windows PowerShell version 3.0 script.
After storage in the default character code of Windows,
please use the PS script. In my japanese enviroment of Windows7 SP1,
the character code is Shift JIS, and new line is \r\n.
Convert to the appropriate character code in English environment.
Input-ja.txt is ManyTime data, character code is UTF-8 without BOM,
new line is \n. Replace \t to the tab character.

PS > .\conv_jst-17b.ps1 input-ja.txt

conv_jst-17b.ps1:
#Read the ManyTime data file, and be converted to the shifted data before 17 hours.

#Creating the input file path
$filepath = Split-Path $MyInvocation.MyCommand.Path
$inputFilePath = Join-Path $filepath $args[0]

#Get the input file contents
$inRecords = Get-Content $inputFilePath -Encoding UTF8

#The output of the input file contents
$inRecords
echo ""

#Set to 17 hours before
$offsetHours = -17
foreach($inRecord in $inRecords)
{
    $anArray = $inRecord.split("`t")
    #String start time of local time.
    $strStartTime = $anArray[0]
    $startTime = [datetime]::ParseExact($strStartTime,"yyyy-MM-dd HH:mm:ss", $null)
    #String end time of local time.
    $strEndTime = $anArray[1]
    $endTime = [datetime]::ParseExact($strEndTime,"yyyy-MM-dd HH:mm:ss", $null)
    #Comment
    $comment = $anArray[2]

    #Draw for 17 hours from the start time
    $startTime = $startTime.AddHours($offsetHours)
    $strStartTime = $startTime.ToString("yyyy-MM-dd HH:mm:ss")
    #Draw for 17 hours from the end time
    $endTime = $endTime.AddHours($offsetHours)
    $strEndTime = $endTime.ToString("yyyy-MM-dd HH:mm:ss")
    #Output
    $newLine = $strStartTime + "`t" + $strEndTime + "`t" + $comment
    $newLine
}

Creation of a garbage collection calendar

It is a garbage collection calendar of the all year by a
self-governing body etc.
The day of garbage collection is as follows.
1: 2nd Monday           Collection of Waste Articles by Children's Association
2: 4th Monday           Large-sized Combustible Trash 
3: Every Week Tuesday   Common Garbage 
4: 1st Thursday         Recycling Garbage 
5: 2nd Thursday         Incombustible Trash 
6: 3rd Thursday         Recycling Garbage 
7: Every Week Friday    Common Garbage 

It works in the terminal on Mac OS X 10.7.5.
The Python 2.7.1 is used on the script.

Below, the garbage collection calendar of 2013 editions is created.
$ python garbage_collection_day.py 2013 > manytime-1.txt

garbage_collection_day.py:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import calendar
# Creation of the start time string.
def startTime(dayStr, num):
    #
    aHour = 0
    #
    if len(str(aHour)) == 1:
        aHourStr = " 0" + str(aHour)
    else:
        aHourStr = " " + str(aHour)
    #
    return dayStr + aHourStr + ":00:00"
# Creation of the end time string.
def endTime(dayStr, num):
    #
    aHour = 23
    #
    if len(str(aHour)) == 1:
        aHourStr = " 0" + str(aHour)
    else:
        aHourStr = " " + str(aHour)
    #
    return dayStr + aHourStr + ":59:00"
# Creation of the yyyy-MM-dd string
def yyyyMMdd(year,month,day):
    #
    if len(str(month)) == 1:
        aMonthStr = "0" + str(month)
    else:
        aMonthStr = "" + str(month)
    #
    if len(str(day)) == 1:
        aDayStr = "0" + str(day)
    else:
        aDayStr = "" + str(day)
    #
    return str(year_num) + "-" + aMonthStr + "-" + aDayStr
# Creation of the data for ManyTime.
def tajikan(aDayStr,aComment):
    startStr = startTime(aDayStr,0)
    endStr = endTime(aDayStr,0)
    return startStr + "\t" + endStr + "\t" + aComment
# Handling the argument
argvs = sys.argv
argc = len(argvs)
# Check the argument
if (argc != 2):
    print 'Usage: # python %s year_num' % argvs[0]
    quit()
# Start main program
year_num = int(argvs[1])
# Processing on a monthly basis.
for month in range(1, 13):
    # Get the calendar.
    c = calendar.monthcalendar(year_num, month)
    # Processing on a weekly basis.
    for week in range(0,len(c)):
        aWeek = c[week]
        # Output 2nd Monday and 4th Monday.
        aDay1 = aWeek[calendar.MONDAY]
        if aDay1 != 0:
            # 2nd Monday
            if week == 2:
                dayStr = yyyyMMdd(year_num,month,aDay1)
                print tajikan(dayStr,"Collection of Waste Articles by Children's Association")
            # 4th Monday
            if week == 4:
                dayStr = yyyyMMdd(year_num,month,aDay1)
                print tajikan(dayStr,"Large-sized Combustible Trash")
        # Output every Tuesday
        aDay2 = aWeek[calendar.TUESDAY]
        if aDay2 != 0:
            #print '%3s: %2s *' % (month, aDay1)
            dayStr = yyyyMMdd(year_num,month,aDay2)
            #print startTime(dayStr,0)
            print tajikan(dayStr,"Common Garbage")
        # Output 1st Thursday, 2nd Thursday and 3rd Thursday.
        aDay4 = aWeek[calendar.THURSDAY]
        if aDay4 != 0:
            # 1st Thursday
            if week == 1:
                dayStr = yyyyMMdd(year_num,month,aDay4)
                print tajikan(dayStr,"Recycling Garbage")
            # 2nd Thursday
            if week == 2:
                dayStr = yyyyMMdd(year_num,month,aDay4)
                print tajikan(dayStr,"Incombustible Trash")
            # 3rd Thursday
            if week == 3:
                dayStr = yyyyMMdd(year_num,month,aDay4)
                print tajikan(dayStr,"Recycling Garbage")
        # Output every Friday.
        aDay5 = aWeek[calendar.FRIDAY]
        if aDay5 != 0:
            #print '%3s: %2s' % (month, aDay2)
            dayStr = yyyyMMdd(year_num,month,aDay5)
            #print startTime(dayStr,0)
            print tajikan(dayStr,"Common Garbage")
# End main program

前の10件 | -

この広告は前回の更新から一定期間経過したブログに表示されています。更新すると自動で解除されます。