Return to Snippet

Revision: 48782
at July 8, 2011 23:20 by adrianparr


Initial Code
var timestampFromBackend:String = "/Date(1310127448000+0100)/";
trace("timestampFromBackend: " + timestampFromBackend);
var formattedTime:String = formatedTimeFromTimestamp(timestampFromBackend);
trace("formattedTime: " + formattedTime);

function formatedTimeFromTimestamp(str:String):String {
	/*
	Might get passed something like this ...
	/Date(1310127448000+0100)/
	but it also works if you are passed ...
	1310127448000+0100	
	*/

	var openBracketIndex:int;
	var closeBracketIndex:int;
	
	if (str.indexOf("(") != -1) {
		openBracketIndex = str.indexOf("(");
	} else {
		openBracketIndex = -1;
	}
	if (str.indexOf(")") != -1) {
		closeBracketIndex = str.indexOf(")");
	} else {
		closeBracketIndex = str.length;
	}

	str = str.substring(openBracketIndex + 1, closeBracketIndex);
	var arr:Array = new Array();
	if (str.indexOf("+") != -1) {
		arr = str.split("+");
		str = arr[0];
	} else if (str.indexOf("-") != -1) {
		arr = str.split("-");
		str = arr[0];
	}
	
	var timestampDate:Date = new Date(Number(str));
	var hrs:String = String(timestampDate.getHours());
	if (hrs.length < 2) {
		hrs = "0" + hrs;
	}
	var mins:String = String(timestampDate.getMinutes());
	if (mins.length < 2) {
		mins = "0" + mins;
	}
	
	str = hrs + ":" + mins;
	return str;
}

// OUTPUT
// timestampFromBackend: /Date(1310127448000+0100)/
// formattedTime: 13:17

Initial URL

                                

Initial Description
I was working on a project where the timestamp string I was getting from the backend developer was pretty dirty in the way it was formatted. For example, it looked like "/Date(1310127448000+0100)/". I needed to get a nicely formatted time from it in the format hrs:mins

Initial Title
AS3 Get formatted time from dirty timestamp string

Initial Tags
date, format

Initial Language
ActionScript 3