user2727195
user2727195

Reputation: 7340

javascript string to time and am/pm format

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

Upvotes: 2

Views: 15199

Answers (4)

Seth Pollack
Seth Pollack

Reputation: 269

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");

Upvotes: 3

Roco CTZ
Roco CTZ

Reputation: 1117

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

Upvotes: 1

Jose Ch.
Jose Ch.

Reputation: 3906

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>

Upvotes: 7

vmontanheiro
vmontanheiro

Reputation: 1039

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"

Upvotes: 0

Related Questions