Javascript date formatting to local timezone with specific format - javascript

I have a date string which is in UTC timezone like this 2015-05-26T14:02:46.000Z
I will convert this to a date object using
var lastModified = "2015-05-26T14:02:46.000Z;
var date = new Date(lastModified);
But when I print this, it prints the date like this Tue May 26 2015 19:32:46 GMT+0530 (India Standard Time)
I want to print the date like this 2015-05-26 7:32:46 PM IST or 2015-05-26 7:32:46 PM GMT+0530
Is there any way to do this?

As hindmost says, it's pretty simple in pure JS. But if you'll be doing this a lot, you may want to look into the powerful MomentJS library.
Using Moment, your code would just be:
moment(date).format('YYYY-MM-DD HH:mm:ss A [GMT]Z')

Date has a number of getter method to get the components of a date. For example date.getHours() will return a number from 0 to 23 for the hour of the day. With each of these pieces you can write the logic to display the date in the format you choose. See the methods Date has here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
If you're looking for a library, MomentJS is the best library I've used for time and dates. It might be too heavy for your needs though. Consider use cases carefully before adding another somewhat large dependency.

Related

the date in Javascript is swapping between day and month in?

I Have date as a string 10/06/1991 when I need to convert to a date object the day and month value is swiping like this Sun Oct 06 1991 00:00:00 GMT+0200 (GMT+03:00), but if I reverse my string to 1991/06/10 it's correct after converting.
is there any idea how to solve it?
You cannot parse string to date using Date object unless it is in ISO form. Here later date - 1991/06/10 is in in correct order so js can make correct date object.
For your case, you can use any other library like moment for parse your given date 10/06/1991 by giving its format to moment, example is given below -
console.log(moment("10/06/1991", "DD/MM/YYYY").toDate());
<script src="https://momentjs.com/downloads/moment-with-locales.min.js"></script>

angular $http.post changing date to UTC date

I was trying to post some data to my REST api which has date.
Now while I debug, my date parameter is a JS Date object with correct date in my timezone: Tue Apr 04 2017 00:00:00 GMT+0530
after it leaves my code, and I see the same in network tab, it is converted to UTC date: "2017-04-03T18:30:00.000Z"
I searched for the solution according to which I need to include locale file of angular in my index.html which I did:
<script type="text/javascript" src="resources/js/angular/angular-locale_en-in.js"></script>
but it doesn't help.
I've seen solutions like adding date format to filter or something, but I want a global solution.
Any help?
Thanks :)
Handling date, time, and timezone have confused me too. May be this answer gives you some insight on how you can handle them.
Try the following code in Chrome's developer console and see how same date is presented in different formats:
var date = new Date();
date.toISOString(); // "2017-04-29T09:54:28.714Z"
date.toGMTString(); //"Sat, 29 Apr 2017 09:54:28 GMT"
date.toLocalString(); //"4/29/2017, 3:24:28 PM"
Any date that you create on client always records the date at zero timezone offset i.e. UTC+/-00:00 Z. For simplicity you may think UTC and GMT as same. When it comes to display purpose the same date is presented as per the browser's timezone. If you do console.log (date) it'll output Sat Apr 29 2017 15:24:28 GMT+0530 (IST) but that doesn't mean that the internal recording of the date is as per browser's timezone. It's just presented on screen/console as per browser's timezone.
Look at date representations not as being converted from one timezone to another but look at them as different representation of the same date. In your browser it is represented as GMT+0530 offset and when it is sent to server it is the same date at zero timezone offset.
As per your comment, if you choose 4th Apr at 00:00 AM in GMT+0530 timezone, internally it'll be 3rd Apr at 18:30 PM in at GMT+0 i.e. zero timezone offset. Let it go to server as it is. When you need to use this date, it comes back from server as 3rd Apr and it'll be displayed in browser as per the browser's timezone offset. There is no conversion involved, it is one date with different representation.
I once asked a related question, may be this adds more clarification.
And overall, this answer is still same as #geminiousgoel and #charlietfl answers.
Scenario :
Send date from UI into API call as an epoch time (UNIX Time) instead of date string. You can use getTime() method to convert the date into epoch time.
var dateStr = "Tue Apr 04 2017 00:00:00 GMT+0530";
var dateEpoch = new Date(dateStr).getTime();
console.log(dateEpoch); // 1491244200000 (Local Time)
At receiver end, they have to convert this epoch time (UNIX time) into Date again.It will give the same local date\time that pass from the UI.
Sample screenshot
Like charlietfl suggested, probably the global hack would be to override Date.prototype.toJSON() method, but that's not a good practice.
Where are you using your $http.post call? The best place to submit an $http request would be in a service. If you use a service, then I suggest you to enwrap your public service API, so that you could have "public" and "private" methods: these could be utilities to perform common operations, such as data transformations, validations..
angular.service('bookStoreService', ['$http'], function($http) {
var normalizeBooks = function(booksArray){
booksArray.forEach(function(book){
// do something on the book
});
};
var updateBooks = function(books){
normalizeBooks(books);
$http.post('myurl', books);
};
return {
updateBooks : updateBooks
};
});
Passing UTC date to server is desired behavior. The client APIs are supposed to handle UTC time instead of assuming the dates are all local dates.
But anyways, you can convert the date to string based on local time zone, and pass the string to server.
i think you just can pass it as string (if the api you use accept strings) with the format you need, let say "Tue Apr 04 2017 00:00:00 GMT+0530" and save it in back-end as string and then when you retrieve it, it will be string and so it will not be changed in any way.
Jindal saab, It will work like this. When we select any date with date picker or just pass any value it takes the original local date but when we pass that value further it converts it into UTC, thereafter it needs to convert to local zone again at receiving end. Database saves date-time in UTC format.
Did you added the angular-locale_en-in.js library to your app? Something like this....
angular.module('myAngularApp', [
'ngLocale'])
Otherwise, the js library won't have any effect in your angular application.
Append UTC at the end so that Browser converts it into UTC date
var dateToServer =new Date(dateFromUser+" UTC");
now the dateToServer will be UTC DateTime format.
Json serializer parse date from string. On a client the date properties are stored as local date in browser time zone. When you are posting your object to server all date properties converts to utc string. In most cases it is a properly behavor. But sometimes you need set and send date in a server time zone. Often it is need when you should set only date whitout time. In that case you should define string propertie and set it manualy. I usaly apply this trick.
class Obj{
d: Date
}
class ObjDto{
constructor(obj: Obj){
this.d= dateTimeToIsoLocalDateString(obj.d)
}
d: string
}
...
export function DateTimeToDate(date) {
return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
}
export function dateTimeToIsoLocalDateString(dateTime: Date): string {
if (dateTime === null) {
return null;
}
let date = DateTimeToDate(dateTime);
let res = date.toISOString().replace("Z", "");
return res;
}
For more understanding this theme you may learn this topic
//in res data of rest service in x the value is date in y value of y-axis
for (const i in res) {
console.log(i);
const a = {x: new Date(this.mimikatzlog[i].x), y: this.mimikatzlog[i].y};
this.policies.push(a);

How can I set up a correct format while doing new Date() in jQuery?

I have a date in a following format:
12/11/2015 07:12 PM
In jQuery I'm doing:
var parsedDate2 = new Date(date);
alert(parsedDate2);
And that prints me:
Fri Dec 11 2015 07:12:00 GMT+0100 (Central European Standard Time)
and that almost works correctly, mostly because in my example (12/11/2015 07:12 PM) the format is DD/MM and not MM/DD. However, jQuery treats it as the month is first. That's a problem, because when I chose as input:
19/11/2015 07:17 PM <--- (19th of November)
I'm getting:
Invalid date
So how can I set up the correct format here with the day before the month?
Ugly, but it work, with JS only :
a = "12/11/2015 07:12 PM";
b = a.split(' ');
c = b[0].split('/');
bad = new Date(a);
alert('bad : '+bad);
good = new Date(c[1]+'/'+c[0]+'/'+c[2]+' '+b[1]+' '+b[2]);
alert('good : '+good);
The other way is to use Moment.js parsing tool
Think that you should use more specialized and focused library along with JQuery, for me the best one is Moment.js - it has all and more than needed to date-time parsing and formatting and doesn't do something else.
Also, there are some other alternatives, like date.js and globalize.js
It's in the form of mm/dd/yyyy. Try 11/19/2015 07:17 PM. Sadly, jQuery doesn't know which format you're using and so, uses the deafult one.
Unfortunately, the Javascript Date system isn't very malleable when it comes to adding date formats. Here is a reference from Mozilla. I think wierdpanda has the right idea, write a function that accepts your date format, reformats it before feeding it to new Date(), and returns the result. Use this in place of where you have new Date(), and all should be good.

Any way to parse a time string using Moment.js but ignore timezone info?

Given the volume of Timezone questions, I would have thought to be able to find the answer to this issue, but haven't had any success.
Is there a way using moment.js to parse an ISO-8601 string but have it parsed in my local timzeone? Essentially I want to ignore the timezone information that is supplied in the ISO string.
For example, if I am in EDT timezone:
var x = moment( "2012-12-31T00:00:00+0000" );
will give me:
"2012-12-30T19:00:00-5000"
I'm looking to ignore the timezone info and just have it give me a moment equivalent of "2012-12-31T00:00:00-5000" local time (EDT).
I don't think you really want to ignore the offset. That would ultimately just be replacing the offset you provided with one from your local time zone - and that would result in a completely different moment in time.
Perhaps you are just looking for a way to have a moment retain the time zone it was given? If so, then use the moment.parseZone function. For example:
var m = moment.parseZone("2012-12-31T00:00:00+0000");
var s = m.format(); // "2012-12-31T00:00:00+00:00"
You could also achieve this with moment.utc. The difference is that moment.parseZone will retain whatever offset you give it, while moment.utc will adjust to UTC if you give it a non-zero offset.
I solved this by supplying a format as the second argument, and using Moment's method of escaping characters, and wrapped square brackets around the timezone.
moment("2016-01-01T05:00:00-05:00", "YYYY-MM-DDTHH:mm:ss[Z]").startOf("hour").format()
This will still create moment objects using your local time zone, but it won't do any sort of auto-timezone calculation. So the above example will give you 5am regardless of timezone supplied.
I know I'm late to the party, I had the same question and my searches didn't bring me any closer. I broke down and read the documentation and there is an option in moment for a String + Format:
String + Format docs
moment(String, String);
moment(String, String, String);
moment(String, String, Boolean);
moment(String, String, String, Boolean);
and more words, then this:
Unless you specify a time zone offset, parsing a string will create a date in the current time zone.
moment("2010-10-20 4:30", "YYYY-MM-DD HH:mm"); // parsed as 4:30 local time
moment("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z"); // parsed as 4:30 UTC
The part that gave me pause was the example that was used to parse local time omitted the +0000, which lead me to think the input string needed to have that removed, but it doesn't.
example:
var time = "2012-12-31T00:00:00+0000";
var x = moment(time); // Sun Dec 30 2012 19:00:00 GMT-0500
var y = moment(time,'YYYY-MM-DD'); //Mon Dec 31 2012 00:00:00 GMT-0500
You can ignore the browser's timezone completely by creating a new moment using moment.utc() instead of moment().
For example, if you are trying to work purely with a UTC date/time of the browser's current time but want to discard its timezone data, you can recreate the browser's current time into a UTC format using the following:
let nowWithTimezone = moment();
let nowInUtc = moment.utc(nowWithTimezone.format('MM/DD/YYYY HH:mm'), 'MM/DD/YYYY HH:mm');
Further documentation on moment.utc(): https://momentjs.com/docs/#/parsing/utc/
If you know for sure your input string is in the ISO-8601 format, you could just strip off the last 5 digits and use that in the Moment constructor.
var input = "2012-12-31T00:00:00+0000"
input = input.substring(0, input.length-5)
moment(input).toString()
> "Mon Dec 31 2012 00:00:00 GMT-0600"
There are valid reasons to do what the OP is asking for. The easiest way to do this with Moment is using its parseZone(date) method. No futzing around with string manipulation or multiple calls. It effectively parses the date string as though it were in the browser's local time zone.
This is difficult task to do with MomentJS, it will basically depend as well on your current timezone.
Documentation as well is vague for this specific task, the way I solved the issue on my side was by adding hours to the date before converting it to JSON format.
var dt = moment("Sun Sep 13 2015 00:00:00 GMT-0400", "ddd MMM DD YYYY HH:mm:ss GMT-0400", false);
var date = dt.add(2, 'hour').toJSON();
console.log(date); //2015-09-13T00:00:00.000Z
Momentjs default logic will format the given time with local timezone. To format original date, I wrote a function:
https://github.com/moment/moment/issues/2788#issuecomment-321950638
Use moment.parseZone to convert without taking into account the timezone.
const moment = require('moment')
const dateStr = '2020-07-21T10:00:00-09'
const date = moment.parseZone(dateStr)
console.log(date.format('MM-DD-YY HH:mm A')) // 07-21-20 10:00 AM
Try here link to docs
The best way is to use:
dt = moment("Wed Sep 16 2015 18:31:00 GMT-0400", "ddd MMM DD YYYY HH:mm:ss GMT-0400",true);
And to display convert again to desired timezone:
dt.utcOffset("-04:00").toString()
output > Wed Sep 16 2015 18:31:00 GMT-0400

Covert Time Returned by Facebook Graph API to readable Time Format

I m getting Time data in this format in an JSON Object.
"created_time": "2012-04-01T15:02:52+0000"
I need to convert this format to some readable time format like
3:02 PST 1 April, 2012
So the users understand it. I m using Jquery for handling this data.
I tried doing it but I m not understanding which time format it is !
You should be able to do something like this, which should actually be human readable:
var date = new Date("2012-04-01T15:02:52+0000")
console.log(date); //Sun Apr 01 2012 17:02:52 GMT+0200 (W. Europe Summer Time)
Using the Date object, you are able to convert it further, should you want.
See http://www.elated.com/articles/working-with-dates/ for some nice examples, like:
date.toDateString(); //Sun Apr 01 2012​​​​​​​​​​​​​​​​​
I guess you want Timeago plugin !

Categories