Momentjs return wrong date after minutes manipulation - javascript

In my php application I set the italian timezone like this way:
date_default_timezone_set('Europe/Rome');
the string above is located in my config.php file, the core of the app. Anyway, from the backend I using momentjs with CodeIgniter framework. When a user select a date from the properly input set this result:
Now I get the value from this input like this:
var end_date_temp = Date.parse($('#end-datetime').val());
And the initial result is wrong:
Tue Mar 01 2016 11:03:00 GMT+0100 (ora solare Europa occidentale)
The rest of code is:
var end_date = moment(end_date_temp).add(serviceDuration, 'minutes').format('DD/MM/YYYY HH:mm');
$('#end-datetime').val(end_date);
NB: I also tried to set moment.locale('it') but the same result appear, in my javascript libraries I've the italian timezone of momentjs. What is wrong?
UPDATE Code:
var end_date_temp = moment($('#end-datetime').val())._i;
var end_date = moment(moment(end_date_temp).add(serviceDuration, 'minutes')).format('DD/MM/YYYY HH:mm');
$('#end-datetime').val(end_date);

// parse the input string to a moment object, **specifying the input format**
var end_date = moment($('#end-datetime').val(), 'DD/MM/YYYY HH:mm');
// manipulate it as desired
end_date.add(serviceDuration, 'minutes');
// format it to the specified output format, and assign the result back to your field
$('#end-datetime').val(end_date.format('DD/MM/YYYY HH:mm'));
You can do this in one line of code if you like.
$('#end-datetime').val(moment($('#end-datetime').val(), 'DD/MM/YYYY HH:mm').add(serviceDuration, 'minutes').format('DD/MM/YYYY HH:mm'));
The locale setting isn't important with this particular bit of code, because you don't use any locale-specific functions or format specifiers

After a lot of attempts, I fixed in my timezone (italian) like so:
moment.locale('it');
var end_date_temp = moment($('#end-datetime').val()).format('DD/MM/YYYY HH:mm')
var end_date = moment(end_date_temp).add(30, 'minutes');
$('#end-datetime').val(moment(moment(end_date).toDate()).format('DD/MM/YYYY HH:mm'));
I declared the .locale as it, in the next time I formatted the time returned from the input text in my timezone as well. I've manipulated the date with the .add method, for do this I've create another instance of momentjs object. At the end I pass the value from the input, re-formatted the date again in my timezone format 'cause in the manipulation I lose the previous formatting. The final result is what I wanted. Hope this help, anyway, if someone find a solution more optimized than my I'll be happy to see.

momentjs is using the american date format (MM/DD/YYYY), enforce a format to get the right date:
var input = '03/01/2016 11:00';
var date = moment(input, 'DD/MM/YYYY HH:mm');
document.write(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.0/moment.min.js"></script>

Related

I get a different date

I need date format like : 2018-10-04T20:35:28. in javascript.
I don't know what format is this, but I already try follow
Now I have this:
var now = new Date();
var isoDate = new Date(now).toISOString();
My output is:
2018-10-05T04:55:58.896Z
But I have a wrong day because actual date is:
Thu 4 Oct 2018 22:56:53 CST
Why i have +1 day in all dates.
like #Nisarg Shah said "The ISO string is in UTC, the one in console is in your local time zone" . You can change it using this
new Date().toLocaleString("en-US", {timeZone: "America/New_York"})
Check this out for more information.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
var isoDate = new Date(now).toISOString();
// Output
2018-10-05T04:55:58.896Z
This isoDate is in UTC. You can see that there is a 'Z' in the end of the string. This means that the date is in UTC.
You can use Moment Timezone (moment.js) to convert any given date to another timezone.
moment.tz('2018-10-05T04:55:58.896Z', 'America/Toronto').format();
Just change the timezone name to the one you want to convert.
For Further Details
https://momentjs.com/timezone/docs/#/using-timezones/

change date format javascript

I need to send a date to a backend service that requires a date in the following format.
I have access to moment also.
I am using an input type of datetime on the front end which sends over a date like this: "2017-05-17T10:00"
I have tried new Date("2017-05-17T10:00"); but this returns Wed May 17 2017 11:00:00 GMT+0100 (BST). I have also tried using some moment methods, but cannot get the correct format.
Does anyone know how I can convert the datetime string - "2017-05-17T11:43" to the following '2017-05-17T10:43:03+0100'?
Try moment.format(). Here is the list for reference https://momentjs.com/docs/#/displaying/format/
var dt = new Date("2017-05-17T10:00");
console.log(dt);
//'2017-05-17T10:43:03+0100'
var z = moment(dt).format("YYYY-MM-DDTHH:mm:ssZZ");
console.log(z);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Your date is in ISO 8601 format. If you have access to Moment.js (as you said) you can use format() method as below:
var date = moment("2017-05-17T10:00").format("YYYY-MM-DDTHH:mmZZ");
console.log(date);
// prints "2017-05-17T10:00-0300"
Try it.

Convert PHP myadmin time string to local time zone(IST) with proper format with moment js

I want to display a GMT date time string to IST(GMT +0530) time format by using moment.js. I am assigning the PHP date time value to a javascript variable and then converting the GMT time to IST time using moment.tz().format(); method. But when I alert the converted value by specifying the format parameters ,the alert is showing the formatted time with chinese letters. moment.js is clearly confusing. Please help me solve this...
GMT Datetime value is "2014-11-28 20:15:26" which is i am getting from PHP variable
"2014-11-29T01:45:26+05:30" is value of Converted value of date time variable to IST by using moment.tz(m,zone).format();
"11月 29日 2014 1:45 早上" is the value of converted value with format parameters moment.tz(m,zone).format('MMM Do YYYY h:mm a');
My code is
var start_dates = '<?php echo $times_start; ?>';
var zone = "Asia/Kolkata";
var m = moment.tz(start_dates,'Europe/London').format();
var time = moment.tz(m,zone).format('MMM Do YYYY h:mm a');
The only way you could get Chinese characters is if you have set the Chinese locale with either the lang or locale functions. You might have done that somewhere else in your script.
With regard to the code you wrote, that interprets the input as the time in London - which is not the same thing as GMT or UTC. (London alternates between GMT and BST for daylight saving time.)
You also don't need to format it just to parse it again.
You just need to do this:
var m = moment.utc(start_dates);
var time = m.tz(zone).format('MMM Do YYYY h:mm a');
This will work for any of the supported zones. But if you know for a fact that you will always be converting to Indian Standard Time, since it doesn't use DST, you don't really need moment-timezone. You can just do this:
var m = moment.utc(start_dates);
var time = m.utcOffset("+05:30").format('MMM Do YYYY h:mm a');

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

Use JavaScript to convert a date string with timezone to a date object in local time

The format of my date string looks like this: yyyy-MM-ddTHH:mm:ss-0Z00
Example 1: 2010-03-05T07:03:51-0800
Example 2: 2010-07-01T20:23:00-0700
I need to create a date object using these date strings. new Date() does not work on this string.
Please help me convert these date strings into a date objects with the local timezone.
Thank you!
Edit: I am using this in Pentaho Data Integration 4.3.0.
Take my timezone as an example (AEST):
function parseDate(str_date) {
return new Date(Date.parse(str_date));
}
var str_date = "2015-05-01T22:00:00+10:00"; //AEST time
var locale_date = parseDate(str_date);
locale_date: Fri May 01 2015 22:00:00 GMT+1000 (AEST)
var str_date = "2015-05-01T22:00:00+00:00" //UTC time
var locale_date = parseDate(str_date);
locale_date: Sat May 02 2015 08:00:00 GMT+1000 (AEST)
You can use a library such as Moment.js to do this.
See the String + Format parsing.
http://momentjs.com/docs/#/parsing/string-format/
The following should parse your date you provided, but you may need to modify it for your needs.
var oldDate = "2010-03-05T07:03:51-0800";
var dateObj = moment(oldDate, "YYY-MM-DDTHH:mm:ssZ").toDate();
Alternatively, see Moment's String parser, which looks like it is in the format you provided, with the exception of a space between the seconds of the time and the time zone.
http://momentjs.com/docs/#/parsing/string/
Alternative
A second way of doing this is Date.js, another library that seems to parse the format just fine. http://www.datejs.com
Date String:
var strDate = "2010-07-01T20:23:00-0700";
To local time representation in native JS Date object:
var ltzDate = (new Date(strDate)).toLocaleString();

Categories