Reputation: 111
I need to get today's midday.
Please don't confuse the post with another StackOverflow post which says "How to get last midday in moments" which is unanswered and want to get the last date.
I want to get the current date not last
For example:
If today is 2020-05-12T22:00:00 should return 2020-05-12T12:00:00 and that's too in the same time zone.
I'm looking for something preexisting function in the moment if it exists.
Is there any method example: moment().someFunction(12, 'd').
Thanks in advance.
Upvotes: 2
Views: 2199
Reputation: 9652
Try using moment-timezone
to specify the timezone . Get the start of the day
and then add 12 hours
to it to give you the desired format
console.log(
moment("2020-05-12T22:00:00")
.tz("America/Los_Angeles")
.startOf("day")
.hour(12)
.minute(0)
.format()
);
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>
Upvotes: 4
Reputation: 721
If you want to get the midday in any way you can do it like this. I didn't use moment.js in this example.
function getMidDate(date){
var dateParts = date.toLocaleString().split(":");
var hour = dateParts[0].replace(dateParts[0].split(" ")[1],"12");
var min = dateParts[1].replace(dateParts[1],"00")
var sec = dateParts[2].replace(dateParts[2],"00");
var middateString = hour + ":" + min + ":" + sec + "+0000";
var midDate = new Date(Date.parse(middateString));
return midDate;
}
var date = new Date();
console.log(getMidDate(date));
Upvotes: 0
Reputation: 179
Get the start of the current day and add 12 hours in it .
var now = moment()
var startdate =now.startOf('day');
var midday = startdate.add(moment.duration(12, 'hours'));
console.log(midday.toString());
Upvotes: 1