javascript convert dates format [duplicate] - javascript

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)

Related

How to convert and Formatting UTC Time to local and dd/mmm/yyyy hh:mm javascrpt

How can i convert the date i get from DB to a certain format.?
this is what I get, 2021-03-30T17:57:53.489Z
I want it to be in format of dd/mmm/yyyy hh:mm in my localtime.
expected output : 30/03/2021 11:27 PM
what I tried so far,
const formatDate = (date) => {
let data = new Date(date);
data = data.toLocaleString('rm-CH', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
return data;
};
console.log(formatDate('2021-03-30T17:57:53.489Z'))
on jsfiddle i get the output like "30-03-2021 23:27"
but on my React native app, when I try this I get output like Tue mar 30 23:27:53 2021.
can someone help me out here.?
PS: My Timezone is India, GMT +5.30. the date string is what I get from my DB(create_date, Postgresql)
A one-liner with fancy string manipulation (spread out to make more readable):
console.log(
new Date()
.toISOString()
.replace(/-/g, '/')
.replace('T', ' ')
.split(':')
.slice(0, -1)
.join(':')
.split(' ')
.map((a, i) => i === 0 ? a.split('/').reverse().join('/') : a)
.join(' ')
);
Or you could just calculate it manually:
const date = new Date(),
pad = (num) => num.toString().length < 2 ? `${'0'.repeat(2 - num.toString().length)}${num}` : num;
console.log(
`${pad(date.getDate())}/${pad(date.getMonth())}/${date.getFullYear()} ${pad(date.getHours())}:${pad(date.getMinutes())}`
);
Or take a shortcut and use a library like Moment.
console.log(
moment().format('DD/MM/yyyy HH:mm')
);
<script src="https://momentjs.com/downloads/moment.js"></script>
I actually figured out a way,
function formatDate() {
var d = new Date('2021-03-30T17:57:53.489Z'),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear(),
hour = d.getHours(),
min = d.getMinutes();
var ampm = hour >= 12 ? 'pm' : 'am';
hour = hour % 12;
hour = hour ? hour : 12; // the hour '0' should be '12'
min = min < 10 ? '0'+min : min;
var strTime = hour + ':' + min + ' ' + ampm;
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return `${day}-${month}-${year} ${strTime}`
}
output : 30-03-2021 11:27 pm

How to get date of today + 00:00:00 in time

I try to get today date + time(00:00:00)
So I do it like this:
const startDate = DateTime.fromISO(params.start)
.startOf('day')
.toFormat('yyyy-LL-dd HH:mm:ss');
But If I do a console.log():
console.log('startData', startDate);
I get an error:
line-chart.service.ts:22 startData Invalid DateTime
So what I have to change?
So I want it to use in here:
return this.sensorNodeService.cameraDataInInterval(
16,
startDate,
'2021-01-20 23:59:59',
'1'
);
let c = new Date(); // take the current time
c.setHours(0);
c.setMinutes(0);
c.setSeconds(0);
// prints the current day at 00:00:00 in your timezone
// in the format 2020-12-02 12:10:12
console.log(c.toISOString().replace(/T/, ' ').replace(/\..+/, ''));
Edit: To format the code in the right way, I used the answer from this question here.
var todaydate = new Date();
var datetime = todaydate.getDate() + "/" +
(todaydate.getMonth() + 1) + "/" +
todaydate.getFullYear() + " " +
+todaydate.getHours() + ":" +
todaydate.getMinutes() + ":" +
todaydate.getSeconds();
console.log(datetime);
Here's how you can do it, for both date/time; or time! :)
function DateTime() {
return (new Date().toLocaleString("en-US", {year: 'numeric',month: 'numeric',day: 'numeric',hour: "numeric",minute: "numeric",second: "numeric",hour12: true}));
}
console.log(DateTime());
function Time() {
return (new Date().toLocaleString("en-US", {
hour: "numeric",
minute: "numeric",
second: "numeric",
hour12: true
}));
}
console.log(Time());

Format Date to MM/DD/YYYY Using toLocaleString

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");
}

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.

Date script doesn't work correctly when is Saturday [duplicate]

The following script calculates me next Friday and next Sunday date.
The problem : the use of .toISOString uses UTC time. I need to change with something that outputs local time. I'm very new to javascript so I can't find the right property to use instead of .toIsostring.
What should I do ?
function nextWeekdayDate(date, day_in_week) {
var ret = new Date(date || new Date());
ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
return ret;
}
let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);
console.log('Next Friday : ' + nextFriday.toDateString() +
'\nFollowing Sunday: ' + followingSunday.toDateString());
/* Previous code calculates next friday and next sunday dates */
var checkinf = nextWeekdayDate(null, 5);
var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
var checkouts = nextWeekdayDate(null, 7);
var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');
If you worry that the date is wrong in some timezones, try normalising the time
To NOT use toISO you can do this
const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB',
{ year: 'numeric', month: '2-digit', day: '2-digit' })
.split("/")
function nextWeekdayDate(date, day_in_week) {
var ret = new Date(date || new Date());
ret.setHours(15, 0, 0, 0); // normalise
ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
return ret;
}
let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);
console.log('Next Friday : ' + nextFriday.toDateString() +
'\nFollowing Sunday: ' + followingSunday.toDateString());
/* Previous code calculates next friday and next sunday dates */
var checkinf = nextWeekdayDate(null, 5);
var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
var checkouts = nextWeekdayDate(null, 7);
var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');
console.log(yyyy, mm, dd)
// not using UTC:
const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB', { year: 'numeric', month: '2-digit', day: '2-digit' }).split("/")
console.log(yyyy1, mm1, dd1)
You are concerned that the [yyyy,mm,dd] is in UTC and not in current timzone?
The nextFriday is a date object. Would it work if you use the get-functions instead?
e.g.
const nextFridayYear = nextFriday.getFullYear();
// get month is zero index based, i have added one
const nextFridayMonth = (nextFriday.getMonth() + 1).toString()
.padStart(2, '0');
const nextFridayDay = today.getDate().toString()
.padStart(2, '0');

Categories

Resources