0 votes
1 view
in Java by (9.5k points)

Below is my code implementation: 

var d = new Date();

var s = "01.00 AM";

d.setTime(s);

The above code doesn’t work. Can anyone tell me how to set the time in 12 hour format as string? 

1 Answer

0 votes
by (19.7k points)

Below is the code which parse time with a regex and set the hours and minutes accordingly: 

var d = new Date(),

    s = "01.25 PM",

    parts = s.match(/(\d+)\.(\d+) (\w+)/),

    hours = /am/i.test(parts[3]) ? parseInt(parts[1], 10) : parseInt(parts[1], 10) + 12,

    minutes = parseInt(parts[2], 10);

d.setHours(hours);

d.setMinutes(minutes);

alert(d);

Interested in Java? Check out this Java Certification by Intellipaat.    

Related questions

0 votes
1 answer
asked Feb 16 in Java by sheela_singh (9.5k points)
0 votes
1 answer
asked Feb 15 in Java by sheela_singh (9.5k points)
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !

Categories

...