How to get the date/time in the original timezone [duplicate] - javascript

This question already has answers here:
How to initialize a JavaScript Date to a particular time zone
(20 answers)
Closed 2 years ago.
My application receives a "dateTtime±timezone" from the API. I'm supposed to show that exact time while formatted with the user defined preference:
var userFormat = "en-US"
var original = "2020-09-01T12:14:05.663-01:23" // strange timezone only to make a point
var date = new Date(original)
console.log(date.toLocaleString(userFormat, {
hour12: false ,
hour : "numeric",
minute: "numeric",
second: "numeric"}))
// expected: "12:14:05"
How can I get a string with the original 12:14:05, not the local time or the GMT time while avoiding string manipulation?

This may work fine:
<script type="text/javascript">
debugger
var userFormat = "en-US";
var original = "2020-09-01T12:14:05.663-01:23";
var time = original.substr(11, 8);
var HH = time.substr(0, 2);
var MM = time.substr(3, 2);
var SS = time.substr(6, 2);
var date = original.substr(0, 10);
var YY = date.substr(0, 4);
var MO = date.substr(5, 2);
var DD = date.substr(8, 2);
var Ndate = new Date(YY, MO, DD, HH, MM, SS);
// sometimes even the US needs 24-hour time
console.log(Ndate.toLocaleTimeString(userFormat, {
hour12: false,
}));
</script>

If you always find this kind of date string you can then split the string and find the time like as below.
var original = "2020-09-01T12:14:05.663-01:23";
var time = original.split('T')[1].split('.')[0];

You could trim the timezone from the string before converting it and then use the normal date methods on the result (e.g. toLocaleString()).
var userFormat = "en-US"
var original = "2020-09-01T12:14:05.663-01:23"
// Trim off the timezone
var date = new Date(original.split('.')[0]);
console.log(date.toLocaleString(userFormat, { hour: 'numeric',
minute: 'numeric',
second: 'numeric'
}))
// Expected: "12:14:05 PM"

Related

Java Script date calculation not working correctly [duplicate]

This question already has answers here:
How to properly add 1 month to current date in moment.js
(4 answers)
Closed 19 days ago.
I am calculating date in JavaScript based on date, frequency and period. When I am calculating date for one month then It is working perfectly but when I am trying to calculate date three monthly or six monthly then below code is not working fine.
CurrentDate value is 01-Feb-2023 and value of X is 3
When I am giving value of x = 1 then below code is giving 1-Mar-2023 which is correct but when I am giving value of x = 3 then it is giving 1-Feb-2024 instead of 1-May-2023.
var x = 3;
CurrentDate = "01-Feb-2023"
var d = new Date(CurrentDate);
console.log(d);
d.setMonth(d.getMonth() + x);
console.log(d);
var lastDate = moment(d.toISOString().slice(0, 10)).format("DD-MMM-YYYY");
console.log(lastDate)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
You have a timezone issue
Also you are wasting moment by not using it to add the month
Note that this date format makes moment complain: '01-Feb-2023'
var x = 3;
var currentDate = moment('01-Feb-2023'); // not a great value for moment
var lastDate = moment(currentDate).add(x, 'M').format("DD-MMM-YYYY");
console.log(lastDate)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
Better: Strict mode is set by passing true as the third parameter to the moment function.
moment('02/01/2023', 'MM/DD/YYYY', true);
var x = 3;
var currentDate = moment('02/01/2023', 'MM/DD/YYYY', true); // better
var lastDate = moment(currentDate).add(x, 'M').format("DD-MMM-YYYY");
console.log(lastDate)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
Without moment - note the new Date(dateString); is STILL not a good idea with "01-Feb-2023" due to Why does Date.parse give incorrect results?
But if you can live with this, then here is a version
const dateTimeFormat = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
const addToDate = (dateString, offset) => {
const currentDate = new Date(dateString); // using the Date.parse. Moment warned it would use this
currentDate.setHours(15, 0, 0, 0) // normalise
currentDate.setMonth(currentDate.getMonth() + offset); // add the month
const [month, sp1, day, comma, year] = dateTimeFormat.formatToParts(currentDate);
return `${day.value}-${month.value}-${year.value}`; // There is no DD-MMM-YYYY in INTL so we make our own
}
let x = 3;
const lastDate = addToDate("01-Feb-2023", x);
console.log("01-Feb-2023 plus",x,"months:",lastDate)

How can I get the epoch time for a specific time of day in a specific timezone?

I'm trying to get the epoch timestamp, for the current day, in a specific timezone.
eg I want to know the epoch timestamp for 6am today in Pacific Standard time
I'm pretty close, but not sure how to adjust for the timezone:
const getTimestampFor10amPST = () => {
const today = new Date()
const year = today.getFullYear()
const month = today.getMonth()
const day = today.getDate()
const timestampFor10amPST = new Date(year, month, day, 10, 0, 0, 0);
return timestampFor10amPST.getTime()
}
How can I get this timestamp for the expected timezone?
You can do this using Luxon:
const dt = luxon.DateTime.fromObject({hour: 10, zone: 'America/Los_Angeles'});
console.log('Time in time zone: ' + dt.toString());
console.log('Unix (epoch) timestamp in milliseconds: ' + dt.toMillis());
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.25.0/luxon.min.js"></script>
This works because when you don't provide date components, Luxon uses the current date in the provided time zone as a basis. Also, when you provide any time components, the remaining time components are set to zero. Thus all you need to set are the hour and time zone.
Try something like this:
function calcTime(city, offset) {
d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000*offset));
return "The local time in " + city + " is " + nd.toLocaleString();
}
// get Bombay time
console.log(calcTime('Bombay', '+5.5'));
// get Singapore time
console.log(calcTime('Singapore', '+8'));
// get London time
console.log(calcTime('London', '+1'));
another way to do it is using the options object as it has a timeZoneName parameter
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// an application may want to use UTC and make that visible
var options = { timeZone: 'UTC', timeZoneName: 'short' };
console.log(date.toLocaleTimeString('en-US', options));
// → "3:00:00 AM GMT"
// sometimes even the US needs 24-hour time
console.log(date.toLocaleTimeString('en-US', { hour12: false }));
// → "19:00:00"
// show only hours and minutes, use options with the default locale - use an empty array
console.log(date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }));
// → "20:01"
If you want it to return a date object instead of a string, the following solution will work for you:
var d = new Date();
var date_object = new Date(formatDate(d.toLocaleString('en-US', { 'timeZone': 'America/New_York', 'hour12': false })));
function formatDate(date){
var date = date.split(', ')[0].split('/');
var time = date.split(', ')[1].split(':');
return date[2]+'-'+date[0]+'-'+date[1]+'T'+time[0]+':'+time[1]+':'+time[2];
}

javascript format date to legible format

I have this code which is getting me the date in a ledgible format but it currently outputs this format 20200819 but I want to convert it to 2020-08-19 is this possible?
This is my code
const dateConverter = (dateIn) => {
var yyyy = dateIn.getFullYear();
var mm = dateIn.getMonth() + 1; // getMonth() is zero-based
var dd = dateIn.getDate();
return String(10000 * yyyy + 100 * mm + dd); // Leading zeros for mm and dd
}
var today = new Date();
console.log(dateConverter(today));
You don't need the converter function for that. Just use toLocaleDateString with a locale that has this format, like Sweden.
To get more certainty about the format, I have added two extensions:
console.log(new Date().toLocaleDateString("en-se"));
// To be explicit about the format of the numerical parts
console.log(new Date().toLocaleDateString("en-se",
{ year: "numeric", month: "2-digit", day: "2-digit" })
);
// To be explicit about the delimiter also:
console.log(new Date().toLocaleDateString("en-se",
{ year: "numeric", month: "2-digit", day: "2-digit" })
.replace(/\D/g, "-")
);
Alternative:
If you don't want to rely on the native toLocaleDateString function, then replace the following line in your code:
return String(10000 * yyyy + 100 * mm + dd)
with:
return String(10000 * yyyy + 100 * mm + dd).replace(/(....)(..)(..)/,"$1-$2-$3");
You can use padStart to create your own string like below, but I would reccomend looking into the date-fns or moment.js libraries, as they can handle this very nicely.
const dateConverter = (dateIn) => {
var year = dateIn.getFullYear();
var month = dateIn.getMonth() + 1; // getMonth() is zero-based
var day = dateIn.getDate();
return year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
var today = new Date();
console.log(dateConverter(today));
You could use template literals to get the format you want, im pretty sure their must be a simpler way but, this is as similar to your code as possible
const dateConverter = (dateIn) => {
var yyyy = dateIn.getFullYear();
var mm = dateIn.getMonth() + 1;
if (mm < 10) mm = `0${mm}`; // getMonth() is zero-based
var dd = dateIn.getDate();
if (dd < 10) dd = `0${dd}`;
return `${yyyy}-${mm}-${dd}`;
};
var today = new Date();
console.log(dateConverter(today));
Output as today : 2020-08-19
new Date().toISOString().slice(0, 10).split('-').reverse().join('/')
//use following date format methods and options.
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// formats below assume the local time zone of the locale;
// America/Los_Angeles for the US
// US English uses month-day-year order
console.log(date.toLocaleDateString('en-US'));
// → "12/19/2012"
// British English uses day-month-year order
console.log(date.toLocaleDateString('en-GB'));
// → "20/12/2012"
// Korean uses year-month-day order
console.log(date.toLocaleDateString('ko-KR'));
// → "2012. 12. 20."
// Event for Persian, It's hard to manually convert date to Solar Hijri
console.log(date.toLocaleDateString('fa-IR'));
// → "۱۳۹۱/۹/۳۰"
// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(date.toLocaleDateString('ar-EG'));
// → "٢٠‏/١٢‏/٢٠١٢"
// for Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
console.log(date.toLocaleDateString('ja-JP-u-ca-japanese'));
// → "24/12/20"
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(date.toLocaleDateString(['ban', 'id']));
// → "20/12/2012"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

How can I get time from ISO 8601 time format in JavaScript?

This is my ISO formatted date. In here I want to get time like "11:00" by JavaScript.
I used this method:
new Date(Mydate).toLocaleString();
But it gave time as "16:30". Is there any format or method to do that in JavaScript? How can I get only time of that time zone.
var Mydate = "2012-10-16T11:00:28.556094Z";
Output will be the "11:00"
Modern approach, using ECMAScript Internationalization API built in to Node.js and most modern browsers:
const myDate = "2012-10-16T11:00:28.556094Z";
const time = new Date(myDate).toLocaleTimeString('en',
{ timeStyle: 'short', hour12: false, timeZone: 'UTC' });
// Output: "11:00"
Older approach, using moment.js:
var myDate = "2012-10-16T11:00:28.556094Z";
var time = moment.utc(myDate).format("HH:mm");
// Output: "11:00"
Use this:
var date = new Date(Mydate);
var time = ConvertNumberToTwoDigitString(date.getUTCHours()) +
":" + ConvertNumberToTwoDigitString(date.getUTCMinutes());
// Returns the given integer as a string and with 2 digits
// For example: 7 --> "07"
function ConvertNumberToTwoDigitString(n) {
return n > 9 ? "" + n : "0" + n;
}
Try this, I forget where I got this:
// --- Date ---
// convert ISO 8601 date string to normal JS Date object
// usage: (new Date()).setISO8601( "ISO8601 Time" )
Date.prototype.setISO8601 = function(string) {
var d, date, offset, regexp, time;
regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
d = string.match(new RegExp(regexp));
offset = 0;
date = new Date(d[1], 0, 1);
if (d[3]) date.setMonth(d[3] - 1);
if (d[5]) date.setDate(d[5]);
if (d[7]) date.setHours(d[7]);
if (d[8]) date.setMinutes(d[8]);
if (d[10]) date.setSeconds(d[10]);
if (d[12]) date.setMilliseconds(Number("0." + d[12]) * 1000);
if (d[14]) {
offset = (Number(d[16]) * 60) + Number(d[17]);
offset *= (d[15] === '-' ? 1 : -1);
}
offset -= date.getTimezoneOffset();
time = Number(date) + (offset * 60 * 1000);
return this.setTime(Number(time));
};
Try this to grab the time from ISO date.
let Mydate = '2012-10-16T11:00:28.556094Z';
let result = Mydate .match(/\d\d:\d\d/);
console.log(result[0]);
The output will be,
11:00
be aware that older implementation of the toLocaleTimeString can behave differently depending on the browser's implementation.
Date: 2021-September-09
The locales and options arguments customize the behavior of the
function and let applications specify which language formatting
conventions should be used. In older implementations that ignore the
locales and options arguments, the locales and the form of the string
returned will be entirely implementation-dependent.
The implementation I recently used:
function getTimeFromISODateString(isoDateString) {
const date = new Date(isoDateString);
const hours = `0${date.getUTCHours()}`.slice(-2);
const minutes = `0${date.getUTCMinutes()}`.slice(-2);
const seconds = `0${date.getUTCSeconds()}`.slice(-2);
return `${hours}:${minutes}:${seconds}`;
}
This answer failed for me for any time of 00:34 as it got changed to 24:34
const time = new Date(myDate).toLocaleTimeString('en',
{ timeStyle: 'short', hour12: false, timeZone: 'UTC' });
It would seem this is a better solution, at least for me.
new Date(value).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
Source:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString

compare string with today's date in JavaScript

I've got a string from an input field which I use for date with a format like this 25-02-2013. Now I want to compare the string with today's date. I want to know if the string is older or newer then today's date.
Any suggestions?
<script type="text/javascript">
var q = new Date();
var m = q.getMonth()+1;
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
</script>
Exact date comparsion and resolved bug from accepted answer
var q = new Date();
var m = q.getMonth();
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can use a simple comparison operator to see if a date is greater than another:
var today = new Date();
var jun3 = new Date("2016-06-03 0:00:00");
if(today > jun3){
// True if today is on or after June 3rd 2016
}else{
// Today is before June 3rd
}
The reason why I added 0:00:00 to the second variable is because without it, it'll compare to UTC (Greenwich) time, which may give you undesired results. If you set the time to 0, then it'll compare to the user's local midnight.
Using Javascript Date object will be easier for you. But as the Date object does not supports your format i think you have to parse your input string(eg: 25-02-2013) with '-' to get date month and year and then use Date object for comparison.
var x ='23-5-2010';
var a = x.split('-');
var date = new Date (a[2], a[1] - 1,a[0]);//using a[1]-1 since Date object has month from 0-11
var Today = new Date();
if (date > Today)
alert("great");
else
alert("less");
If your date input is in the format "25-02-2013", you can split the string into DD, MM and YYYY using the split() method:
var date_string="25-02-2013";
var day = parseInt(date_string.split("-")[0]);
var month= parseInt(date_string.split("-")[1]);
var year = parseInt(date_string.split("-")[2]);
The parseInt() function is used to make the string into an integer. The 3 variables can then be compared against properties of the Date() object.
The most significant points which needs to be remembered while doing date comparison
Both the dates should be in same format to get accurate result.
If you are using date time format and only wants to do date comparison then make sure you convert it in related format.
Here is the code which I used.
var dateNotifStr = oRecord.getData("dateNotif");
var today = new Date();
var todayDateFormatted = new Date(today.getFullYear(),today.getMonth(),today.getDate());
var dateNotif=new Date(dateNotifStr);
var dateNotifFormatted = new Date(dateNotif.getFullYear(),dateNotif.getMonth(),dateNotif.getDate());
Well, this can be optimized further but this should give you clear idea on what is required to make dates in uniform format.
Here's my solution, getDay() doesn't work like some people said because it grabs the day of the week and not the day of the month. So instead you should use getDate like I used below
var date = new Date();
var m = date.getMonth();
var d = date.getDate();
var y = date.getFullYear();
var todaysDate = formateDate(new Date(y,m,d));
console.log("Todays date is: " + todaysDate)
const formateDate = (assignmentDate) => {
const date = new Date(assignmentDate)
const formattedDate = date.toLocaleDateString("en-GB", {
day: "numeric",
month: "long",
year: "numeric"
})
return formattedDate
}
The function below is just to format the date into a legible format I could display to my users
<script type="text/javascript">
// If you set the timezone then your condition will work properly,
// otherwise there is a possibility of error,
// because timezone is a important part of date function
var todayDate = new Date().toLocaleString([], { timeZone: "Asia/Dhaka" }); //Today Date
var targetDate = new Date('2022-11-24').toLocaleString([], { timeZone: "Asia/Dhaka" });
console.log('todayDate ==', todayDate); // todayDate == 10/31/2022, 12:15:08 PM
console.log('targetDate ==', targetDate); // targetDate == 11/24/2022, 6:00:00 AM
if(targetDate >= todayDate)
{
console.log("Today's date is small");
}
else
{
console.log("Today's date is big")
}
</script>

Categories

Resources