2

I've a time in string format

var start = "14:00:00"

and I need the output to be

02:00pm

<span>{{session.start | some-format}} to {{session.end}}<span>

or javascript manipulation (any will do)

I looked up this page but it needs some kind of time stamp I guess.

https://docs.angularjs.org/api/ng/filter/date

user2727195
  • 7,122
  • 17
  • 70
  • 118

4 Answers4

7

Do something like:

function toTime(timeString){
    var timeTokens = timeString.split(':');
    return new Date(1970,0,1, timeTokens[0], timeTokens[1], timeTokens[2]);
}

var start = "14:00:00";
var date = toTime(start);

then apply the angular filter:

<span>{{date | date:'h:mm a'}} to {{session.end}}<span>
Jose Ch.
  • 3,856
  • 1
  • 20
  • 34
  • just a little more help please, how could I use the date constructor with your solution above `new Date(year, month[, day[, hour[, minute[, second[, millisecond]]]]]);` to make my code less verbose, as I've to do the same for session.end – user2727195 Nov 10 '14 at 01:26
  • how about this `var tokens = sessions[i].start.split(":"); sessions[i].start = new Date(null, null, null, tokens[0], tokens[1], tokens[2]);` – user2727195 Nov 10 '14 at 01:29
3

Using moment you can do something like this:

var timeArr = "14:00:00".split(':');

var date = new Date().setHours(timeArr[0], timeArr[1], timeArr[2])

var startTime = moment(date).format("h:mm:ss A");

var endTime = moment().format("h:mm:ss A");
BFree
  • 102,548
  • 21
  • 159
  • 201
Seth Pollack
  • 269
  • 2
  • 13
1

I saw you mentioned angular documentation in the question so if you are after an Angular approach you can give it a try with this:

$scope.start = new Date();
{{ start | date: 'shortTime'}}

Example here: Plnkr

Roco CTZ
  • 1,107
  • 1
  • 16
  • 31
0

Try this

function timeConvert (time) {
  time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];

  if (time.length > 1) { 
    time = time.slice (1);  
    time[5] = +time[0] < 12 ? 'AM' : 'PM';
    time[0] = +time[0] % 12 || 12;
  }
  return time.join ('');
}

timeConvert ('19:00:00');

out: "7:00:00PM"

vmontanheiro
  • 1,009
  • 9
  • 12