JavaScript date displaying the wrong day and time - javascript

I have this application where I want to use you date, but the problem is that the date is not working as I expect.
I create a date object like this:
// Get today's date
today: function () {
// Create a new date
var date = new Date();
// Set to midnight
date.setHours(0, 0, 0, 0);
// Return our date
return date;
},
and If I output that date in my view I get yesterdays date at 23:00 hours....
Which looks like this:
2015-07-08T23:00:00.000Z
Does anyone know how I can get the date to be formatted properly?
Update
Just to elaborate a bit, I want to use the date to compare against records in the database. These records have the date applied to them, because the JavaScript is showing the local date time, it is not comparing correctly. Also there is a case where I am saving that date and I don't want it to save the local date.

based on your culture setting you can use the
date.toLocaleDateString()
this will give localized string format back

date.toUTCString();
date.toLocaleString();
date.toLocaleDateString();
date.toDateString();
date.toISOString();
Find your answer here :) And the best option is to use momentjs http://momentjs.com/

So, I ended up creating this function:
// Converts a date to a timeStamp
this.convertToTimeStamp = function (dateTime) {
// Get just the date
var date = dateTime.toDateString();
// Get the timestamp
var timeStamp = Date.parse(date);
// Return our timeStamp
return timeStamp;
};
If my understanding is correct, that should create the same date no matter what timezone / locale you are in.

Related

How to get the current time to an existing date in JavaScript?

I'm trying to add the current time to an existing date but I'm not sure how to do it.
I'm importing stuff into a Postgres database and need a ISO string to update the "updatedAt" column, the imported stuff only has a date like this tho: "2022-03-15", no time.
How would I add the time to this and turn it into a proper ISO string for my database?
const date = new Date('2022-03-15')
const iso = date.toISOSTring() // how to add the current time?
-
Should look like this: "2022-03-15 09:36:54.292613"
Thank you! :)
Try to use dayJs and add the time that you need, https://day.js.org/docs/en/parse/string
dayjs('2018-04-04T16:00:00.000Z')
dayjs('2018-04-13 19:18:17.040+02:00')
dayjs('2018-04-13 19:18')
You can set the time units into date from the current date-time i.e. new Date().
const date = new Date("2022-03-15");
const now = new Date();
date.setHours(now.getHours());
date.setMinutes(now.getMinutes());
date.setSeconds(now.getSeconds());
date.setMilliseconds(now.getMilliseconds());
console.log(date.toISOString());
console.log(date.toISOString().replace("T", " ").replace("Z", " "));

How to format timestamp to a calendar format date?

I'm using devExtreme dxScheduler and i'm trying to display meetings after fetching them from api, the problem is that i can't recreate the original date format ("YYYY-MM-DDThh:mm:ssZ") since i'm getting the dates as timestamp.
Here is how it's stores :
var startDate = moment("2021-05-24T16:30:00.000Z").valueOf()
// 1621873800000
Here is what i'm trying to do to recreate the format:
var startDate = moment(new Date(startDate)).format("YYYY-MM-DDThh:mm:ssZ")
//"2021-05-24T07:30:00+03:00"
Notice that the original date ("2021-05-24T16:30:00.000Z") and the formatted date ("2021-05-24T07:30:00+03:00") are different ...hence the calendar do not displays them.
Looks like the date is being converted into your local timezone, thus the difference. You may need to add Moment Timezone to be able to get the timezone back in to recreate it to the format you need. Also consider adding utc() before the format to bring it to Zulu time.
Fix 1
I see from the DevExtreme page that it needs to be displayed within this format:
currentDate: new Date(2021, 4, 27)
Maybe you need to format it before adding it like this:
var check = moment("2021-05-24T16:30:00.000Z", 'YYYY/MM/DD');
var month = check.format('M');
var day = check.format('D');
var year = check.format('YYYY');
console.log(month,day,year);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
And then in your dxScheduler add the property like this:
currentDate: new Date(year, month, day);
Fix 2
If that's not the problem, you can install moment-timezone
var a = moment.utc("2013-11-18 11:55").tz("Asia/Taipei");
var b = moment.utc("2013-11-18 11:55").tz("America/Toronto");
a.format(); // 2013-11-18T19:55:00+08:00
b.format(); // 2013-11-18T06:55:00-05:00
a.utc().format(); // 2013-11-18T11:55Z
b.utc().format(); // 2013-11-18T11:55Z
In this example, you first create moment.utc("2013-11-18 11:55") object in UTC, and then change its timezone to specified. This also works if you create the object in your default timezone: moment("2013-11-18 11:55").
Note that created moments have equal UTC time because these moments were created in a default timezone.
Turns out that displaying a calendar event with DevExtreme requires only to use regular date object.... so no need to do anything spacial.

How do I get the next day's date in JS in YYYY-MM-DD format?

Seems like a simple question, but all the timezone ins and outs in JS are causing me a bunch of headaches.
Basically, if I have a date like the following:
2018-04-06
I want to be able to get the next day's date as such:
2018-04-07
I found the following snippet on SO for doing this (kind of):
var date = new Date('2018-04-06');
date.setDate(date + 1);
The problem is that I'm getting the date back with the adjusted timezone, and because I'm in the US ET timezone, it's giving me that date minus five hours, which is actually the same day as where I started.
I've been through countless SO posts trying to find an answer to this seemingly simple question, but for any given date, regardless of the timezone the user is in, how do I get the next day's date in YYYY-MM-DD format? Thank you.
Strings in the format YYYY-MM-DD are parsed as UTC so in this case, do everything in UTC (see Why does Date.parse give incorrect results? and How can I add 1 day to current date?).
The toISOString method will return the string in the required format, just trim the redundant time part, e.g.
let s = '2018-04-06';
let d = new Date(s);
d.setUTCDate(d.getUTCDate() + 1);
console.log(d.toISOString().substr(0,10));
Did you try with the UTC date?
var date = new Date('2018-04-06');
console.log(date.toUTCString());
date.setDate(date.getDate() + 1);
console.log(date.toUTCString());
As it was suggested by #chrisbyte, have your tried to use toUTCString method instead of toString() method ?
As a reminder , toString is the default used when you display the date object withim the console for example
I think the "problem" you're assuming is just an incomplete understanding how Date.toString() method behaves: this method seems to to return string representing a Date object but seems to use timezone as mentionned here (on the comment in 1st example)
Here my snippet to understand more:
const originalDate = new Date('2018-04-06');
// retrieving the original timestamp
const originalTimestamp = originalDate.valueOf()
// displaying the original date (non UTC / UTC)
console.log(`original date (timezone dependent): ${originalDate.toString()}`)
console.log(`original date (timezone independent): ${originalDate.toUTCString()}`)
// we add one more day
originalDate.setDate(originalDate.getDate() +1)
const dayAfterTimestamp = originalDate.valueOf()
// displaying the original date (non UTC / UTC)
console.log(`updated date (timezone dependent): ${originalDate.toString()}`)
console.log(`updated date (timezone independent): ${originalDate.toUTCString()}`)
// check the differences (in milliseconds)
console.log(`difference: ${(dayAfterTimestamp-originalTimestamp)}`)
// displaying the original format (timezone independent)
At last if you want to return the date string as a YYYY-MM-DD format you may have to implement it yourself :-/ , or use toLocaleFormat method but it isn't standardized.
The logic would be to add 24 hours in milliseconds to the current time. As an example:
var myDate = new Date();
var oneMoreDay = new Date();
oneMoreDay.setTime(myDate.getTime() + 86400000);
console.log(myDate.getDate());
console.log(oneMoreDay.getDate());
An additional day has been added to the oneMoreDay variable. In your specific example you just wanted to add one more day to the ORIGINAL variable, so i'd do something such as:
date.setTime(date.getTime() + 86400000);

How can I convert this string "07/10/2017 18:30 PM" to JavaScript Date type

I am trying to read all dates in a table and see if those dates are old dates than current date time and if those are old dates then highlight those dates with some color.
Here is my Javascript code
$(".ticket-gird-td-duedate").each(function(i, e) {
debugger;
var dueDateAsString = $(e).text();
console.log(dueDateAsString);
var dueDate = new Date(dueDateAsString);
var currentdate = new Date();
if (dueDate < currentdate) {
//mark date in red color
console.log("I need to change color for this date as this is past date" + dueDate);
}
});
Problem here is dueDateAsString comes as "07/10/2017 18:30 PM"
And when I am doing
new Date("07/10/2017 18:30 PM")
it fails with invalid date error
Invalid Date
How can I convert my string date to Javascript date and proceed to compare it with current date?
That isn't a valid date, as you either have 24hr format or AM|PM 12hr format.
This works:
new Date('07/10/2017 18:30'); // No 'PM' after the 24hr time
Also note that JS dates are mutable, so todayDate and check will hold the same date value, but check will be a number.
You call this one first
todayDate.setDate(todayDate.getDate() - 5);
It will update todayDate to 5 days ago. Then you just assign it to check or you todayDate further.
var check = todayDate;
Hope this helps.
You can do this by using moment.js library (yet another terrific way to achieve date parsing).
Moment.Js library is freely available. You can use either a minified or full version of this library as you require. In this
library all the operations are performed on a moment object so the
date or time is stored in this library as a moment object only. So
this moment object is the core of this entire library. You can find
this library at Moment.js site's home page.
Add momentjs library reference into your project - https://momentjs.com/downloads/moment.js
updated code with moment.js would be:
var todayDate = new moment().format("MM/DD/YYYY h:mm:ss a");
var yesterday = todayDate.toLocaleString();
var check = moment(todayDate, "MM/DD/YYYY h:mm:ss a").add('days', -5);
alert("Your Old Date is- " + todayDate);
alert(check);
alert("Your Old Date is- " + yesterday);
JavaScript fiddle

Convert date time in utc

i have to convert date in utc from locale date time in birt.
The only problem is that the date is divide in two numeric data type like '20131012' instead for 'yyyyMMdd' and '223112'instead for 'h24:mi:ss'.
Can anyone help to convert this two data type affected from locale settings, with other two in UTC mode?
thanks for anyone just read this..
Javascript Date objects are based on a UTC time value. When methods such as date.toString are called, the local system settings are used to show a local date and time.
You can use Date.UTC to create a UTC time value, use that to create a date object, then use the date object to get a local (system) equivalent date and time.
e.g.:
var utcDate = '20131012';
var utcTime = '223112';
// Get a UTC time value
var timeValue = Date.UTC(utcDate.substring(0,4),
utcDate.substring(4,6) - 1, // Months are zero indexed
utcDate.substring(6),
utcTime.substring(0,2),
utcTime.substring(2,4),
utcTime.substring(4)
);
// Convert time value to date object
var date = new Date(timeValue);

Categories

Resources