There are two different problems here that you should mentally separate:
- Parsing a string in the particular format of
YYYY-MM-DD hh:mm:ss
to a Date
object.
- Adding minutes to a
Date
object.
Parsing the String
You should be aware that the parsing behavior when you pass a string to the Date
constructor is implementation specific, and the implementations vary between browser vendors.
- In general, when dashes (
-
) are present, the values are treated as UTC, and when slashes (-
) are present, the values are treated as local to the time zone where the code is running.
- However, this only applies when either a time is not present, or when the date and time components are separated with a
T
instead of with a space. (YYYY-MM-DDThh:mm:ss
)
- When a space is used to separate date and time components, some browsers (like Chrome) will treat it as local time, but other browsers (like IE and Firefox) will consider it an invalid date.
- Replacing the space with a
T
will allow the date to be parsed, but if that's all you do, then Chrome will treat it as UTC, while IE and Firefox will treat it as local time.
- If you also add the trailing
Z
, (YYYY-MM-DDThh:mm:ssZ
) then all browsers will parse it as UTC.
If you want a format that all browsers will recognize as local time, there is only one, and it's not ISO standard: YYYY/MM/DD hh:mm:ss
. Thus, you might consider:
var s = "2014-06-07 01:00:00";
var dt = new Date(s.replace(/-/g,'/'));
Adding Minutes
This is much more straightforward:
dt.setMinutes(dt.getMinutes() + 15);
That will simply mutate the Date
value to add 15 minutes. Don't worry about overflow - if getMinutes
returns 55, setting 70 minutes will properly add 1 hour and 10 minutes.
A Better Solution
Moment.js removes all of the guesswork about parsing variations, and gives you a much cleaner API. Consider:
// parse a string using a specific format
var m = moment("2014-06-07 01:00:00","YYYY-MM-DD HH:mm:ss");
// adding time
m.add(15, 'minutes');
// format the output as desired, with lots of options
var s = m.format("L h:mm:ss A");