unable to get the date format - javascript

I'm trying to change the date format in javascript where in a variable i m getting the date value like this "11/09/2019" and want to change in a format like this "11-09-2019".but somehow i'm getting this format "sat nov 09 2019" whereas it should be "tue sep 11 2019".
can anyone help me. any help would be appreciated.
var alt_date1 = "11/09/2019";
var date = new Date(alt_date1);
alert(date);
output: Sat Nov 09 2019 00:00:00 GMT+0530 (India Standard Time)

If I understand your question right, you want a different format i.e., "-" instead of "/" and you're also getting the wrong date? 2 days ahead? Depending on your environment (browser, node, etc) the Date API can behave differently. I think this link might help you: JavaScript's getDate returns wrong date (Not sure though, some answers pertain to the time zones it uses)
As for formatting look here:
https://codehandbook.org/javascript-date-format/
Example from that site:
let current_datetime = new Date()
let formatted_date = current_datetime.getDate() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getFullYear()
console.log(formatted_date)
// output
"19-10-2018"

It's a little bit tricky to understand the question fully, but if you don't need a Date object, and you want to just format the string as 11-09-2019 it can be achieved with the simple replace function like this:
alt_date1.replace(/\//g, '-')

Related

how to convert milliseconds to gmt time using javascript

I have a project where if the end date is set for February 12 (can be set to any future date), the following is obtained from the API response.
project: {endDateTime:"1518393600000"}
For UTC time and date, this response corresponds to Mon Feb 12 2018 00:00:00
For local time and date, the response corresponds to Sun Feb 11 2018 19:00:00 (GMT - 05:00)
On the UI, I need to show the end date as Feb 12, 2018, but the date is getting converted to the local date and time zone and shows Feb 11 as the end date. My code is below:
var d = new Date();
var c = d.setTime(parseInt($scope.project.endDateTime));
$scope.endDateTime = c;
In the html
<div> {{endDateTime}} </div>
I tried modifying the code in the following way but it did not work.
var d = new Date($scope.project.endDateTime);
var c = d.getUTCDate();
$scope.endDateTime = c;
I tried to tune the code in other ways but could not get it to work. I know similar questions have been asked before but still could not get it to work, even after spending several hours. Maybe I am missing something very trivial. Some help would be greatly appreciated. :)
I have figured out the solution. My code and explanation is as follows
var d = new Date(parseInt($scope.project.endDateTime));
var c = c.toUTCString();
var endDate= c.split(" ");
$scope.endDateTime = endDate[2] + ' ' + endDate[1] + ',' + ' ' + endDate[3];
And the html is
<div> {{endDateTime}}</div>
I needed to parse the string that came back from the API response. Missed this part and also the correct method is toUTCString(), not getUTCDate().
So basically what happens is if the end date is set to Feb 12(in this case, it is dynamic though), the API returns
project: {endDateTime:"1518393600000"}
The first line of the code parses the string and if I do a console.log(d) I get this: Sun Feb 11 2018 19:00:00 GMT-0500 (Eastern Standard Time).
Now I need to display the time in GMT so the toUTCString() method was used in the second line and doing console.log(c) I get: Mon, 12 Feb 2018 00:00:00 GMT
The requirement is to show the date as Feb 12, 2018 on the UI, so I split the string in the third line and if i do console.log(endDate) I get
["Mon,", "12", "Feb", "2018", "00:00:00", "GMT"]
From the output of the third line, it was pretty easy to show the required date format. Hope this helps.

Convert past datetimes using JS with browser support

toLocaleString() is deprecated but seems to lack replacement
I have a website where I store member post dates in this format: YYYY-MM-DD HH:MM:SS
The problem is that these dates are all stored with the timezone UTC and I want to convert these dates using JS to the users OS timezone. I know I could just ask users to input their timezone but I would like to try something new which require as little user interaction as possible. The goal of the site is to make a forum which is incredibly easy and straightforward to use.
I have almost gotten it to work the way I want but it currently only supports Chrome it seems like. This is not good enough since I plan on having a lot of users.
Since the timezone offset varies it is not good enough to only retrieve the current time offset which a lot of topics here seem to suggest. I want to accurately display for e.g. registration dates.
This is my current solution (timezone test only supports chrome as far as I can tell) it is also implemented on the whole website which is in beta.
https://ingsan.net/timezone/
Source code below
var d = new Date();
var tzName = d.toLocaleString('en', {timeZoneName:'short'}).split('').pop();
var cusid_ele = document.getElementsByClassName('timestamp');
for (var i = 0; i < cusid_ele.length; ++i) {
var timestamp = cusid_ele[i];
timestamp.innerHTML += " "+tzName;
t = new Date(timestamp.innerHTML);
usertime = t.toLocaleString()
timestamp.innerHTML = usertime;
}
I have used this site for years without asking but this time I seem to be unable to find a topic similar enough to mine.
The method I use which might be questionably is simply replacing objects inside the assigned class name. I plan to do other classes for other format outputs.
<p>Register date: <span class="timestamp">2016-01-31 20:12:55</span></p>
If you got a solution to this issue I would very much appreciate it. I am no professional and never went to any course but I have managed to make ingsan.net on my own. Help a humble student out ;)
If all you're doing is converting from UTC to the browser's local time zone, you do not need to actually try to figure out what time zone that is. Just be sure your input is clearly identified as UTC, and the default behavior of the Date object is to display values in the browser's local time zone.
var input = "2016-01-31 20:12:55";
var d = new Date(input + " UTC");
var s = d.toString();
The resulting string will vary by implementation and time zone, such as (a few examples):
"Sun Jan 31 2016 12:12:55 GMT-0800 (Pacific Standard Time)"
"Sun Jan 31 2016 15:12:55 GMT-0500 (Eastern Standard Time)"
"Mon Feb 01 2016 01:42:55 GMT+0530 (India Standard Time)"
"Mon Feb 01 2016 09:12:55 GMT+1300 (New Zealand Daylight Time)"
This will work in all browsers. The only problem is that you don't have control over the format of the output string. That's where toLocaleString can help, though as you pointed out - it's not necessarily implemented in all browsers. However, you seemed to think it was deprecated, and it is not. It's actually part of a newer specification (ECMA-402), which just is not widely implemented everywhere (yet).
You have other options though. You could build the output string yourself, like this:
var z = function(x) {return x < 10 ? '0' + x : x};
var s = d.getFullYear() + '-' + z(d.getMonth() + 1) + '-' + z(d.getDate()) + ' '
+ z(d.getHours()) + ':' + z(d.getMinutes()) + ':' + z(d.getSeconds());
Of course you could figure out how to adjust to 12 hour format, use different separators, different date-field ordering (YMD vs DMY vs MDY), etc.
Or, you could just use a library such as moment.js which is already equipped for that.
var input = "2016-01-31 20:12:55";
var m = moment.utc(input).local(); // parse as UTC, then switch to local mode
var s = m.format(); // use any of the format parameters you wish

JavaScript Changes My Date Based on Browser Time Zone

I am trying to create a Date object in JavaScript, passing a string like this:
2014-11-30T00:00:00.0000000
However, the value of the Date object is:
Sat Nov 29 2014 17:00:00 GMT-0700 (Mountain Standard Time)
It changed it to 11/29 when I want 11/30. Is there any way I can make the date 2014-11-30, regardless of what time zone the browser is in?
Note: One possible workaround is to use the Date(year, month, day) constructor; however, I am constructing the data in a JSON string, which doesn't appear to support this.
EDIT:
Actually, I just did a test and created a date using Date(2015, 1, 1) and it gives me:
Mon Feb 02 2015 00:00:00 GMT-0700 (Mountain Standard Time)
So I can't even create a date that way and have it be the date I want. I don't understand why this is so difficult.
You can use Date.UTC
The UTC() method differs from the Date constructor in two ways.
Date.UTC() uses universal time instead of the local time.
Date.UTC() returns a time value as a number instead of creating a Date
object.
EDIT - why does SO insist on making links so hard to spot? That, up there, is a link to the docs in case that wasn't obvious.
EDIT 2 - I think I misunderstood. Try this:
var d = new Date('2014-11-30T00:00:00.0000000');
var utc = new Date(
d.getUTCFullYear(),
d.getUTCMonth(),
d.getUTCDate(),
d.getUTCHours(),
d.getUTCMinutes(),
d.getUTCSeconds()
);
alert('d: ' + d + "\n" + 'utc: ' + utc);

javascript timestamp doesn't works in FireFox and in IE [duplicate]

I have an existing date time string in place
new Date('2014-08-01T00:00:00')
But instead of returning 2014-08-01, it returns as 2014-07-31 in the actually angularJS view.
I wonder is this date time string valid, if not, why its not valid.
Could the T be the reason that the string return a wrong date?
The console.log return a date of Thu Jul 31 2014 20:00:00 GMT-0400 (EDT)
Thank You
Lets call those -2 are toxic vote downs. They should really recall the days when they are struggling to understand the basic concepts that now apparant to them. Its a shame.
At present (Autumn 2014), JavaScript's date/time format diverges from ISO-8601 in a very important way: If there's no timezone indicator on the string, it assumes Z ("Zulu", GMT).
So
new Date('2014-08-01T00:00:00')
...is August 1st at midnight GMT. If you live east of GMT, that will be on the 31st in your local time.
However, this incompatibility with ISO-8601 is being fixed in ES6 and some implementations (including the latest V8 in Chrome) are already updating it. The ES6 spec changes the default to local time; check out ยง20.3.1.15 ("Date Time String Format", the section number may change) in the draft PDFs or this unofficial HTML version.
The displayed date uses the timezone of your browser/computer. This means that if you are in GMT-1 and you enter 2014-08-01T00:00:00, the actual date is 2014-08-01T00:00:00 - 1 hour = 2014-07-31T23:00:00
I have this date in startdate=2021-10-27T00:00:00-04:00,
d=new Date(data.StartDate) // outputTue Oct 26 2021 23:00:00 GMT-0500
But date is getting one day before'Tue Oct 26 2021 23:00:00 GMT-0500' in central timezone(below -6,-7,-8...).
Actually I used this it is working fine but for central timezone not working
var d = new Date(data.StartDate);
console.log(data.startDate);
$scope.txtStartDate = ("0" + (d.getMonth() + 1)).slice(-2) + "/" + ("0" + d.getDate()).slice(-2) + "/" + d.getFullYear();

JavaScript convert date to format

I'm trying to truncate a JavaScript Date object string from:
Wed Aug 01 2012 06:00:00 GMT-0700 (Pacific Daylight Time)
to
Wed Aug 01 2012
(I'm not particular, could be of format MM/DD/YYYY for example, as long as I get rid of the time/timezone)
Essentially I just want to get rid of the time and the timezone because I need to do a === comparison with another date (that doesn't include the time or timezone)
I've tried using this http://www.mattkruse.com/javascript/date/index.html but it was to no avail. Does anyone know how I can format the existing string such as to get rid of the time? I would prefer to stay away from substring functions, but if that's the only option then I guess I'll have to settle.
Edit: I'm open to options that will compare two date objects/strings and return true if the date is the same and the time is different.
The only way to get a specific format of date across different browsers is to create it yourself. The Date methods in ECMAScript are all implementation dependent.
If you have a date object, then:
// For format Wed Aug 01 2012
function formatDate(obj) {
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var months = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'];
return days[obj.getDay()] + ' ' + months[obj.getMonth()] +
' ' + obj.getDate() + ' ' + obj.getFullYear();
}
Though a more widely used format is Wed 01 Aug 2012
Use the Date object's toDateString() method instead of its toString() method.
SIDE BY SIDE DEMO
Even so, it might be better to compare the two date objects directly:
Compare two dates with JavaScript

Categories

Resources