Format Date to MM/DD/YYYY Using toLocaleString - javascript

In JS, how can I get the date to format to MM/DD/YYYY?
new Date(Date.now() + (8 * 86400000)).toLocaleString().split(',')[0])
returns "12/1/2020"
How can I format it to "12/01/2020"?
fromDate:
(new Date(Date.now() + (1 * 86400000)).toLocaleString().split(',')[0]),
toDate:
(newDate(Date.now() + (8 * 86400000)).toLocaleString().split(',')[0])
I would like the fromDate and toDate to be:
If between 5:00 PM MST and Midnight: set fromDate to tomorrow's date , and toDate to tomorrow's date + 7 days
How can compare the currentTime to say if it is greater than 5 PM local time?
let currentTime = new Date().toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
});

You can use the options argument in .toLocaleString to format your date as "MM/DD/YYYY"
var currentDate = new Date(Date.now() + (8 * 86400000))
var newDateOptions = {
year: "numeric",
month: "2-digit",
day: "2-digit"
}
var newDate = currentDate.toLocaleString("en-US", newDateOptions );
console.log(newDate)
A detailed post on how to use the arguments in .toLocaleString - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

This from another post here.
var currentD = new Date();
var startHappyHourD = new Date();
startHappyHourD.setHours(17,30,0); // 5.30 pm
var endHappyHourD = new Date();
endHappyHourD.setHours(18,30,0); // 6.30 pm
console.log("happy hour?")
if(currentD >= startHappyHourD && currentD < endHappyHourD ){
console.log("yes!");
}else{
console.log("no, sorry! between 5.30pm and 6.30pm");
}

Related

Convert the local time to another time zone with this JavaScript

I need to increase the current date in Moscow time by 1 day every time the clock is 15:00 and more. I did it at local time, but I can’t do it according to Moscow time (UTC + 3)
function date() {
const today = new Date();
const t = today.getHours();
const dtfRU = new Intl.DateTimeFormat('ru', {
month: 'long', day: '2-digit',
});
if (t >= 15) {
today.setDate(today.getDate() + 1);
document.querySelector('.date').innerHTML = dtfRU.format(today);
} else document.querySelector('.date').innerHTML = dtfRU.format(today);
}
document.addEventListener("DOMContentLoaded", date);
I found a solution here: enter link description here I needed to do something like this:
function calcTime() {
const now = new Date();
const utc = now.getTime() + (now.getTimezoneOffset() * 60000);
const d = new Date(utc + (3600000 * 3));
const h = d.getHours();
const dtfRU = new Intl.DateTimeFormat('ru', {
month: 'long', day: '2-digit',
});
if (h >= 15) {
const newd = new Date(utc + (3600000 * 3 * 9));
document.querySelector('.date').innerHTML = dtfRU.format(newd);
} else document.querySelector('.date').innerHTML = dtfRU.format(d);
}
document.addEventListener("DOMContentLoaded", calcTime);
You can retrieve the local hour in Moscow as follows:
// Get a DateTimeFormat object for the hour in Moscow in 24-hour format
const dtf = Intl.DateTimeFormat('en', {
timeZone: 'Europe/Moscow',
hour: 'numeric',
hour12: false
});
// The above will create a format that has only the hour, so you can just use it.
const hour = +dtf.format();
console.log("hour:", hour);
Alternatively, if you decide you need more than just the hour, use formatToParts. For example:
const dtf = Intl.DateTimeFormat('en', {
timeZone: 'Europe/Moscow',
hour: 'numeric',
hour12: false,
minute: 'numeric'
});
const parts = dtf.formatToParts();
const hour = +parts.find(x => x.type === 'hour').value;
const minute = +parts.find(x => x.type === 'minute').value;
console.log("hour:", hour);
console.log("minute:", minute);
You can then use that in the rest of your code however you wish.

javascript how to change date now format [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 2 years ago.
I am facing an issue with javascript dates. I want to change the format of date
this.setState({
current: Date(Date.now()),
}, 1000);
//convert minutes
//if minutes are 0 to 29 then show current hours reset the minutes again start with 0 like 18:00
//if minutes are 29 to 59 then show current hours reset the minutes again start with 30 like 18:30
var slotTime1 = currentdate.getHours() +':'+ (currentdate.getMinutes() <= 29 ? '00' : '30') ; //10:30
Output:
Thu May 14 2020 10:00:30 GMT+0500 (Pakistan Standard Time)
Expected
10:00:52 AM
10:30 AM
What should I change?
You can simply use Date toLocaleTimeString() method like:
const current = new Date()
const timestring = current.toLocaleTimeString()
console.log( timestring ) //=> 10:47:52 AM
The toLocaleTimeString() method returns a string with a language sensitive representation of the time portion of the date.
To only get hh:mm a format you can pass option object to the toLocaleTimeString() method like:
const current = new Date()
const timestring = current.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
console.log( timestring ) //=> 10:50 AM
With setState:
this.setState({
current: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
});
var date=new Date();
console.log(date.getHours() + ":" + date.getMinutes()+ ":" + date.getSeconds() + " " + date.getHours()<12 ? 'AM' : 'PM'}`);
OUTPUT : 11:9:37 AM
date.getHours()<12 results in AM between 12Am to 11:59 AM and after 11:59 it results in PM

javascript convert dates format [duplicate]

This question already has answers here:
How to add 30 minutes to a JavaScript Date object?
(29 answers)
Closed 2 years ago.
I am facing an issue in javascript dates. I want to display previous and after 30min
How should I added previous or after 30min in current dates.
this.setState({
current: new Date().toLocaleTimeString(), //10:30:02 PM
slotTime: new Date().toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit'
}), //10:30 AM
Output:
10:30 AM //current date
expected:
10:00 AM //previous
10:30 AM //current
11:00 AM //after 30min
anyone help me?
You can simply do it like this:
var currDate = new Date();
var dd = new Date().setMinutes(currDate.getMinutes() - 30); //reduce 30 minutes
var ddPLus = new Date().setMinutes(currDate.getMinutes() + 30); //add 30 minutes
var reductedTime = new Date(dd);
var addedTime = new Date(ddPLus);
console.log("Current time: ", new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })) //current time
console.log("Reduced time: ", reductedTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })) // reduced time by 30mins
console.log("Added time: ", addedTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })) // added time by 30mins
Hope this help
/* required:
* - timestamp => number of timestamp format
* - format => return format, ex. format 1 (23:59:59), format 2 (23:59)
* return: time with string
*/
function timestampToTime(timestamp, format = 1) {
if (!isNaN(timestamp) || timestamp != undefined) {
let dd = new Date(timestamp)
if (format == 1) {
return ('00' + dd.getHours()).slice(-2) + ':' + ('00' + dd.getMinutes()).slice(-2) + ':' + ('00' + dd.getSeconds()).slice(-2)
} else if (format == 2) {
return ('00' + dd.getHours()).slice(-2) + ':' + ('00' + dd.getMinutes()).slice(-2)
}
} else {
return null
}
}
let dd = + new Date()
let previous = timestampToTime(dd - (1.8e+6)) // 1.8e+6 = 30 min
let current = timestampToTime(dd)
let after = timestampToTime(dd + (1.8e+6)) // 1.8e+6 = 30 min
console.log(previous)
console.log(current)
console.log(after)

Convert Date format from mm-dd-yyyy to yyyy-mm-dd in javascript

I am trying to convert Date format from mm-dd-yyyy to yyyy-mm-dd in javascript. I tried below code getting Invalid date.
var convertJSDate = function(dateTime)
{
var dateTime = dateTime.split(" ");
var dateArr = dateTime[0].split("-");
//var timeArr = dateTime[2].split(":");
var date1= new Date(dateArr[2],dateArr[0],dateArr[1],0,0,0,0);
return date1;
}
var startTime = convertJSDate("06-08-2015");
Here, I want to display the startTime as 2015-06-08 00:00:00. Now I am getting return date1 as Invalid date. I don't know where is the issue.
Please help me.
I corrected your code, like that it should work:
var convertJSDate = function(dateTime)
{
var dateArr = dateTime.split("-");
var date1= new Date(dateArr[2] + "-" + dateArr[0] + "-" + dateArr[1]);
return date1;
}
var startTime = convertJSDate("06-08-2015");
If you want to format the date in JavaScript, you may consider using moment.js.
http://momentjs.com/
Based on what I see from the documentation, the library may awesomely fit your need. With moment.js you can format Date like in C#:
moment().format('MMMM Do YYYY, h:mm:ss a'); // June 8th 2015, 8:15:34 pm
moment().format('dddd'); // Monday
moment().format("MMM Do YY"); // Jun 8th 15
moment().format('YYYY [escaped] YYYY');
Above are excerpt from moment.js documentation.
Format any date in YYYY-MM-DD format in Javascript
let date = (fecha) => {
let f = fecha.split('T')
let nf = (f[1] !== undefined) ? [f[0], f[1].slice(0,10)].join(' ') : f;
let d = new Date(nf)
let q = d.toLocaleString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' }).split('/')
let s = d.toLocaleString('en-US', { second: 'numeric',hour: '2-digit', minute: '2-digit', hour12: true })
return [q[2],q[0],q[1]].join('-') +' '+ s;
}
console.log(date('2019-01-09T11:43:05.000+00:00'))

Moment.js diff of two moments defined by week and weekday gives wrong result

I want to calculate the difference between a moment (itemMoment) and now (nowMoment) defined by weekday, hour and minute. If the itemMoment is before nowMoment (diff < 0) I want to add one week and calculate the difference again, but the addition of a week (week: week + 1 in my code )somehow doesn't change the difference and I still get a negative difference.
It's the first time I use the moment.js library so may be I don't get it how to use it correctly. Would be great if an experienced used could help.
var now = moment();
var year = now.year();
var week = now.week();
var weekday = now.weekday();
var hour = now.hour();
var minute = now.minute();
var itemMoment = moment({
day: item.weekday,
hour: item.hour,
minute: item.minute
});
var nowMoment = moment({
day: weekday,
hour: hour,
minute: minute
});
if (itemMoment.diff(nowMoment) > 0) {
item.date = moment({
year: year,
week: week,
weekday: item.weekday,
hour: item.hour,
minute: item.minute
});
diff = itemMoment.diff(nowMoment);
}
else {
if (week == 51) {
week = -1;
year = year + 1
}
item.date = moment({
year: year,
week: week + 1,
weekday: item.weekday,
hour: item.hour,
minute: item.minute
});
diff = item.date.diff(now);
you can just do comparison using isBefore() or isAfter(). http://momentjs.com/docs/#/query/
if (itemMoment.isBefore(nowMoment)) {
Then you can do manipulation like so: http://momentjs.com/docs/#/manipulating/
item.date = itemMoment.add('weeks', 1);

Categories

Resources