Javascript date format today Asia GMT+8 - javascript

In my country, today is 12/15/2022, I'm from Asia which is gmt+8.
Basically I want my date to be 2022-12-15T00:00:00.000Z instead of showing 2022-12-14T16:00:00.000Z.
here is the code:
const today = new Date().toLocaleDateString();
console.log(new Date(today));
But I really want it to be exact like this
2022-12-15T00:00:00.000Z
is it possible without using logic "add +8 hours"?

One way is to run your code in UTC zone so that you don't accidentally create dates in different time zones. You can set TZ='UTC' environment variable for this.
Otherwise you can create the date like this.
const today = new Date().setUTCHours(0, 0, 0, 0); // note 'today' is a number now
> console.log(new Date(today))
2022-12-15T00:00:00.000Z

you can force your time zone like this
console.log(new Date(new Date().toLocaleDateString('en', {timeZone: 'Asia/Hong_Kong'})))
Edit:
changed toLocaleString to toLocaleDateString
this should meet your needs now

You can first convert the date to a local date string, then parse the year, month and day from it to construct the local ISO zero date string:
const localDate = new Date().toLocaleDateString('en', {timeZone: 'Asia/Hong_Kong'});
console.log('localDate:', localDate);
let m = localDate.match(/(\d+)\/(\d+)\/(\d+)/);
let localZero = m[3] + '-' + m[1] + '-' + m[2] + 'T00:00:00.000Z';
console.log('localZero:', localZero);
Output:
localDate: 12/15/2022
localZero: 2022-12-15T00:00:00.000Z

Related

How to convert a date to ISO format but with timezone info in place of the 'Z' in Javascript?

I have always worked with dates in ISO format that ends with a 'Z'. But now I have to replace that 'Z' with timezone info like +08:00.
In other words, currently I have this format 2020-01-17T00:30:00.000Z, but now I need it in this format 2020-01-17T08:30:00+08:00.
Looks like popular date library like moment and dayjs convert date to ISO format without 'Z' too by default. Is that still considered an 'ISO' date format? And I can't find out how to do it with vanilla Javascript and doing the .toISOString() always gives me the 'Z'..
If you get the date string in the ISO format, but you want to get the string in a certain timezone, with the timezone.
Then here's a simple function that does just that.
function getISODateStampWithTZ (date, tzHours)
{
let dateTz = new Date(date);
dateTz.setUTCHours(tzHours);
return dateTz.toISOString().replace(/Z$/,
(tzHours<0 ? '-' : '+') +
(Math.abs(tzHours)<10 ? '0'+Math.abs(tzHours) : Math.abs(tzHours)) +
':00');
}
const date = new Date('2020-01-17T00:30:00.000Z');
console.log(date.toISOString());
console.log(getISODateStampWithTZ(date, 8));
console.log(getISODateStampWithTZ(date, -1));
Such function could also be added to the Date prototype.
The example below prefixes the function with 'custom' to make it distinct from standard methods.
Date.prototype.customToISOStringTZ = function (tzHours)
{
let dateTz = new Date(this);
dateTz.setUTCHours(tzHours);
return dateTz.toISOString().replace(/Z$/,
(tzHours<0 ? '-' : '+') +
(Math.abs(tzHours)<10 ? '0'+Math.abs(tzHours) : Math.abs(tzHours)) +
':00');
}
const date = new Date('2020-01-17T00:30:00.000Z');
console.log(date.toISOString());
console.log(date.customToISOStringTZ(8));
console.log(date.customToISOStringTZ(-1));
parser.isoparse('2019-08-28T14:34:25.518993Z')
use this to get correct format
The Z ("Zulu") on the end means UTC, ie. an offset from UTC of zero. I'm assuming you want to convert from UTC to local time, in which case you need to calculate the offset from UTC:
function convertUTCDateToLocalDate(date) {
const newDate = new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
const offset = date.getTimezoneOffset() / 60;
const hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
Usage:
const date = new Date("2020-01-17T00:30:00.000Z")
const newDate = convertUTCDateToLocalDate(date)
newDate.toISOString() // "2020-01-17T01:30:00.000+01:00"
Beware! This solution won't work for timezones where the offset isn't a full hour.
If you're running this in a browser I'd strongly recommend using a tool like moment.

Convert a AM/PM date string to JavaScript date using jQuery

I have a date string like this 20/09/2018 12:00 AM. I need to stop to put the previous date than today. I have searched the web for it, but no answer found with this format.
I need the default date format of JavaScript so that I can compare with new Date() value. When I use the following format it show the message that says invalid date because of my dd/MM/yyyy hh:mm tt format.
alert(new Date("20/09/2018 12:00 AM"));
Igor recommended using moment.js to solve this — it is a widely used date/time library.
With moment.js you can do this:
var m = moment("20/09/2018 3:14 PM", "DD/MM/YYYY h:mm a");
var d = m.toDate();
The first line creates a "moment" object by parsing the date according to the format string specified as the second argument. See http://momentjs.com/docs/#/parsing/
The second line gets the native javascript Date object that the moment object encapsulates; however, moment can do so many things you may not need to get back that native object.
See the moment docs.
Your format isn't valid, thus you're getting invalid date error. So, using your format(dd/MM/yyyy hh:mm tt) we'll grab the year, month, day, hours and the minutes, then we'll reformat it as an acceptable format by the Date constructor and create a Date instance.
Here's a function that do all what being said and returns a Date instance which you can compare it with another Date instance:
function convertToDate(str) {
// replace '/' with '-'
str = str.replace(/\//ig, '-');
/**
* extracting the year, month, day, hours and minutes.
* the month, day and hours can be 1 or 2 digits(the leading zero is optional).
* i.e: '4/3/2022 2:18 AM' is the same as '04/03/2022 02:18 AM' => Notice the absence of the leading zero.
**/
var y = /\-([\d]{4})/.exec(str)[1],
m = /\-([\d]{2}|[\d])/.exec(str)[1],
d = /([\d]{2}|[\d])\-/.exec(str)[1],
H = /\s([\d]{2}|[\d]):/.exec(str)[1],
i = /:([\d]{2})/.exec(str)[1],
AMorPM = /(AM|PM)/.exec(str)[1];
// return a Date instance.
return new Date(y + '-' + m + '-' + d + ' ' + H + ':' + i + ' ' + AMorPM)
}
// testing...
var str1 = '20/09/2018 12:00 AM';
var str2 = '8/2/2018 9:00 PM'; // leading zero is omitted.
console.log(convertToDate(str1));
console.log(convertToDate(str2));
The Date depends on the user's/server's location, two users may have
different results.
Learn more
about Date.
Hope I pushed you further.

New date() returning next date instead of today's date

i am trying to convert a string into date type.i am giving the string value to new date().
but it's returning next day date instead of date which i am trying to convert.
var endDate = new Date("2017-03-23T23:59:59.000Z");
//end date value is now ------ Fri Mar 24 2017 05:29:59 GMT+0530 (India Standard Time).
Please suggest me how can get correct date in the format MM/DD/YYYY
This hack can help you,
var endDate = new Date("2017-03-23T23:59:59.000Z").toISOString();
it will give you,
"2017-03-23T23:59:59.000Z"
Further if you want to convert it to DD/MM/YYYY then you can use native javascript or lib like moment for that,
This simpile js will help to convert it to any format.
var endDate = new Date("2017-03-23T23:59:59.000Z").toISOString();
var d1 = endDate.split('T'); //spliting date from T
var d2 = d1[0].split('-'); //getting date part
console.log('yyyy/MM/dd', d2[0] + "/" + d2[1] + "/" + d2[2]) //YYYY/MM/DD
console.log("DD/MM/YYYY", d2[2] + "/" + d2[1] + "/" + d2[0])
jsfiddle link
if your time is in IST use below
var endDate = new Date("2017-03-23T23:59:59.00+0530");
If you check dates, you will see that your dates differs in 5h 30 mins, that is same as your date saying GMT +0530. Your original date has .000Z that is time zone of GMT +0.
Make sure you use same time zone when working with date.
Try using Date.UTC('your date')
JavaScript Date objects carry no timezone information. The only reason you saw a non-UTC date is that the browser chooses by default to display dates as local time in the console. If you don't care about the date object aligning with the exact instant in local time, you can use the following format function to turn it into MM/DD/YYYY format:
function format (date) {
var mm = ('0' + (date.getUTCMonth() + 1)).slice(-2)
var dd = ('0' + date.getUTCDate()).slice(-2)
var yyyy = date.getUTCFullYear()
return mm + '/' + dd + '/' + yyyy
}
var endDate = new Date("2017-03-23T23:59:59.000Z")
console.log(endDate.toISOString())
console.log(format(endDate))
(Credit to Ranj for posting an answer using Date#toISOString before mine.)
I have created the solution over here please find below link
https://www.w3schools.com/code/tryit.asp?filename=FD0YSGRMB59W

Parse date in javascript issues

I get such date in javascript
var val = "1960-05-15T20:00:00"
But if I do
var date = new Date(val);
The data I get is one day later:
1960-05-16 // I use this to obtain it: Ext.Date.format(new Date(val), 'm/d/Y')
Can you help me how to parse this date? and get correct date with 1960-05-15?
Your date format is ISO 8601 represented as the local time with an offset to UTC appended.
The Ext.Date singleton support this format with the c flag.
var parsedDate = Ext.Date.parse('1960-05-15T20:00:00', 'c');
var dateStr = Ext.Date.format(parsedDate, 'Y-m-d');
// "1960-05-15"
Have a look at the Sencha ExtJs 6.2.1 documentation Ext.Date for further informations.
You can use native JS to accomplish the output of the Date object in to this format yyyy-mm-dd
Like so:
var val = '1960-05-15T20:00:00';
var d = new Date(val);
var date = d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2);
console.log(date);
When you do
var a = new Date(someDate)
variable a contains date according to your local timezone.
If you want date in same format as you entered , use toISOString method
var a = (new Date(someDate)).toISOString()
My recommendation would be, you can only assume the timezone from where the date is coming from. If you know exactly where that date is coming from, a.k.a London, New York, Sidney, etc... then you can use momentjs to set the UTC offset
var val = "1960-05-15T20:00:00"
// these are equivalent
moment(val).utcOffset("+08:00");
moment(val).utcOffset(8);
moment(val).utcOffset(480);
So the OP has said they're in
Tbilisi, Georgia GMT + 4.00
so
moment(val).utcOffset("+04:00");

What is the proper way to create a timestamp in javascript with date string?

I have date format returned as 05-Jan, 12-feb etc.. when i convert current date using date object in javascript . I did something like this
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth(),
curr_day = curr.getDay(),
today = new Date(curr_year, curr_month, curr_day, 0, 0, 0, 0);
console.log(today);
Here the today is returned as invalid date i needed the create a timestamp which should not include minutes secs and millisecs as zero for date comparison of month and date alone based on that i can categories .Is there way to dynamically create a date and compare those dates for given format.
And when i try to convert my date string using date object it returns year as 2001. how can i compare dates based upon current year.
For eg: in php i have used mktime to create a date dynamically from given date format and compare those results. Any suggestion would be helpful. Thanks.
You can leverage the native JS Date functionality to get human-readable date strings for time stamps.
var today = new Date();
console.log( today.toDateString() ); // Outputs "Mon Feb 04 2013"
Date comparison is also built in.
var yesterday = new Date();
yesterday.setDate( yesterday.getDate() - 1);
console.log( yesterday.toDateString() ); // Outputs "Sun Feb 03 2013"
console.log( yesterday < today ); //Outputs true
You can use the other built-in methods to fine-tune this comparison to be/not be sensitive to minutes/seconds, or to set all those to 0.
You said that you used mktime() in php, so what about this?
change to this :
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth()+1,
curr_day = curr.getDay(),
today = curr_month+'/'+curr_day+'/'+curr_year;
console.log(today);
(getMonth()+1 is because January is 0)
change the :
today = curr_month+'/'+curr_day+'/'+curr_year;
to whatever format you like.
I have found a way to convert the date into timestamp i have tried as #nbrooks implemented but .toDateString has built in date comparison which works for operator < and > but not for == operator to do that i have used Date.parse(); function to achieve it. Here it goes..
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth(),
curr_day = curr.getDate(),
today = new Date(curr_year, curr_month, curr_day, 0,0,0,0);
var dob = new Date('dob with month and date only'+curr_year);
if(Date.parse(dob) == Date.parse(today)){
//Birthdays....
}
This method can be used to create a timestamp for dynamically created date.Thanks for your suggestions.

Categories

Resources