Angular Pipe (or just Javascript) to Convert 24 Time to 12 Hour Format

I’m storing time in my database as 24 hour format (ie: “13:00” [1:00 PM]) because it’s easy and has a bunch of advantages. But on the front-end, in Angular, I want to show these as a 12 hour format. One way to do this is with a Pipe that will allow you to transform the time to 12 hour. Before creating the below I looking for something existing, but didn’t find anything that seemed to fit and work well, so below is what I use.

This is the function in the pipe (can be used in Javascript for those w/o Angular): (try in jsfiddle)

var time24To12 = function(a) {
    //below date doesn't matter.
    return (new Date("1955-11-05T" + a + "Z")).toLocaleTimeString("bestfit", {
        timeZone: "UTC",
        hour12: !0,
        hour: "numeric",
        minute: "numeric"
    });
};

When called and passed a time, like:

time24To12('13:00')

It will return the 12 hour version:

1:00 PM

Okay, so how to add a new Pipe and use it in Angular?

  1. Create a new file “time24to12.pipe.ts
  2. File contents should be the below:
import { Pipe, PipeTransform } from '@angular/core';


@Pipe({ name: 'time24to12Transform' })
export class Time24to12Format implements PipeTransform {
  transform(time: any): any {
    
 var time24To12 = function(a) {
    //below date doesn't matter.
    return (new Date("1955-11-05T" + a + "Z")).toLocaleTimeString("bestfit", {
        timeZone: "UTC",
        hour12: !0,
        hour: "numeric",
        minute: "numeric"
    });
};

    return time24To12(time); 
  }
}

3. Make sure in your app.module.ts you import this file:

import { Time24to12Format } from './time24to12.pipe';

…and also add it to the declarations section:

@NgModule({
  declarations: [
   ...
    Time24to12Format,
 ...

4. Now you can use it in views, like below:

{{yourobject.time | convertFrom24To12Format}}

Hope this helps someone. No, this code doesn’t check beforehand for correct time input formatting or perform many other things it should, it just trusts you.

Angular Pipe (or just Javascript) to Convert 24 Time to 12 Hour Format

Renaming a local file in Cordova / PhoneGap

A few folks have asked “how do I simply rename a local file in Cordova?” Well, to start, you’ll need the file plugin from Apache Cordova. If you don’t already have this, run the below to add the file plugin.

cordova plugin add org.apache.cordova.core.file

Then, you can use the “moveTo” function to rename the file. Below is a reusable function I utilize to pass the current file name, directory, the new file name and a function that happens when the rename is successful.

You can utilize the below function like:

//to call the function. 'renameSuccess' is an function that is used as the success event if the rename is okay
renameFile('somefile.xml','myapp/xml/','new.xml', renameSuccess);

//the function
function renameFile(currentName, currentDir, newName, successFunction) {

    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {

        fileSystem.root.getFile(currentDir + currentName, null, function (fileEntry) {
            fileSystem.root.getDirectory(currentDir, {create: true}, function (dirEntry) {
                parentEntry = new DirectoryEntry(currentName, currentDir + currentName);

                fileEntry.moveTo(dirEntry, newName, function () {

                    successFunction();

                }, renameFail);
            }, renameFail);
        }, renameFail);

    }, renameFail);
}

//and the sample success function
function renameSuccess() {
    alert('renamed!');
}

//and the sample fail function
function renameFail() {
    alert('failed');
}

I’m not saying this is the ‘best’ way to do this, so feel free to comment on improvements!

Renaming a local file in Cordova / PhoneGap

Installing & starting with PhoneGap on Windows for cross platform mobile development

Build-BotPhoneGap is a great framework for creating cross platform apps (Android, iOS, BB, WM, etc.) using HTML, CSS, and JavaScript and uses Apache Cordova™. Installing and testing on Windows takes little setup, below I’ve tried to cover all of the steps needed to get going. My setup / guide below uses Windows 7, 64 bit, it seems like many steps, but in reality is pretty easy.

  1. Install node.js from nodejs.org (use default settings).
  2. Open a command prompt (cmd) and run:
    1. npm install -g phonegap
    2. npm install -g ant
    3. npm install –g cordova
    4. Now add ‘C:\Users\<yourusername>\AppData\Roaming\npm\node_modules\ant\ant\bin’ to the Path system variable
    5. Download and extract the Android SDK from https://developer.android.com/sdk/index.html
      1. I extracted to c:\mobile\androidsdk (referenced below as <yoursdkpath>)
      2. Add <yoursdkpath> + \sdk\platform-tools to the Path system variable
      3. Add <yoursdkpath> + \sdk\tools to the Path system variable
      4. Now to setup an Android image to emulate and test with:
        1. In the sdk folder, run Eclipse (ie: C:\mobile\androidsdk\eclipse\eclipse.exe
        2. Create or use the default workspace
        3. In Eclipse, under Window choose Android SDK Manager
        4. In the SDK Manager, make sure these are checked:
        5. i.      Tools > SDK Tools, Platform-tools
        6. ii.      Android <you choose the version> SDK Platform, Arm system image & Intel system image (if available)
        7. iii.      Extras > Android Support Library, Google USB Driver, Intel x86 emulator HAXM
  3. Click Install x Packages, accept all licenses
  4. When downloads are finished, close the SDK Manager
  5. If you want to speed up the Android emulator, I suggest installing the Intel HAXM located at: \sdk\extras\intel\Hardware_Accelerated_Execution_Manager
  6. Now back in Eclipse (restart if you’ve installed the HAXM), you can go to Window > Android Virtual Device Manager.
  7. Click “New” to create a new virtual device
  8. Choose a name (anything you want)
  9. Choose a device (something simple like the “4.0” WVGA”)
  10. Choose a target (this is what you downloaded in step 4d).
  11. In CPU, choose Intel if it’s available (it’s not required, but if it’s not available, double check the HAXM install and the download the Intel system image for your target version)
  12. Now you can click “OK”
  13. In the list of virtual devices, choose your new device and click “Start”
  14. Provided you don’t see any errors, after a few minutes (be patient) you’ll have a working Android emulator going. android-emulator
  15. Now, let’s do a quick project and test it! Go back to cmd (your command prompt).
  16. Create your project with, run: cordova create hello com.ex.hello “HelloChris”
  17. Go to the project directory, run: cd hello
  18. Add android to the project, run: cordova platform add android
  19. To make sure your project is ok, run: cordova build
  20. Now if you don’t already have your emulator running, go back into Eclipse into the Android Virtual Device Manager and start your device.
  21. When it’s running, run: cordova emulate android
  22. That’s it; you should see “your” app on the emulator in a few seconds. (It reads “device ready” with a logo or something…).

Continue reading “Installing & starting with PhoneGap on Windows for cross platform mobile development”

Installing & starting with PhoneGap on Windows for cross platform mobile development

Tweet button / link without javascript – HTML only

Twitter buttonIf you’ve ever wanted to include a ‘Tweet’ button or link but didn’t want to use the popular Tweet Button code from Twitter (it uses a remote javascript function), there is an alternate approved method called “Intents”. This function works great for instances when simple HTML is preferred (emails, pages geared toward older or simple browsers, etc.). However it doesn’t provide extras like showing how many have used the button or creating the image automatically. So how does it work?

Using Twitter’s Web Intents, you can create links like below:

<a href="http://twitter.com/intent/tweet?url=http://chrisbitting.com
&text=Checkout this awesome blog.&via=chrisbitting&hashtags=twitter"
 title="Tweet" target="_blank">Tweet</a>

Which looks like: Tweet

No Javascript!

Be sure to check the documentation for more options and details: https://dev.twitter.com/docs/intents

Tweet button / link without javascript – HTML only

Setting a cookie to expire in javascript

cookietimeAdding and setting a cookie via javascript is pretty simple. Sometimes you want the cookie to expire in a certain amount of time, below is the method is use to calculate an expiration:

//create a date object
var date = new Date();
//add the current date + some seconds 
//(below I add 300 seconds or 5 minutes). 
//The 1000 is milliseconds
 date.setTime(date.getTime() + (300 * 1000));
//convert the future date to universal time
var expires = date.toUTCString();
//set the cookie using whatever method / function you choose.
setCookie('cookiename', 'cookievalue', expires);

For the fun of it, below is the function I use to set cookies:

function setCookie(cname, cvalue, expires) {
 document.cookie = cname + "=" + escape(cvalue) +
 ((expires) ? "; expires=" + expires : "");
}

And since we’re talking about cookies, here is a collection of great cookies recipes you can actually eat!

Setting a cookie to expire in javascript

Titanium Studio / SDK – Deploying To Android Device Issue

Titanium SDK is a great tool for developing cross platform mobile apps. But if you’ve got a Samsung Galaxy (S3 or S4) and noticed that with the new updates, even with USB Dev Debug on, Titanium still can’t deploy to your device, chances are you just need to install the Samsung ADB driver. Below is the official link. [Beware of non-Samsung links on the web.]

http://developer.samsung.com/android/tools-sdks/Samsung-Andorid-USB-Driver-for-Windows

 

Titanium Studio / SDK – Deploying To Android Device Issue