Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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
0 votes
1 answer
asked Feb 16, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer
asked Feb 15, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer

Browse Categories

...