When you go to https://worldtimeapi.org/api/timezone/Europe/Berlin it says raw_offset=3600 , i'm trying to get this value in Node.JS. Need help please, i'm giving my code below but it's giving me wrong output
const moment = require("moment-timezone");
let timezone = "Europe/Warsaw";
let haha = moment().tz(timezone);
let timezone_raw = haha.utcOffset()
Doesn't look wrong they just use a different format.
Worldtime-API seems to use seconds where moment.js seems to use minutes.
According to my test moment.js also returns 60 from utcOffset().
You can either take the raw_offset and divide it by 60 (seconds per minute) to get 60 (minutes).
Or you can take the return from utcOffset() and multiply it by 60 to get 3600.
Related
I wanted to change time at date type which returning from mongodb with custom time like below
"2021-05-26T00:00:00.000Z"
to
"2021-05-26T10:20:00.000Z"
I wanted to change time from a variable at the date, so my technique was split this date with "T" then get time part and change it with custom time
let splitedTime = timev[0].validFrom.toString().split()[0];
let customTime = "10:20:00.000Z";
let finalTime = splitedTime + customTime;
but this split not working this giving me date like this "Wed May 26 2021 06:00:00 GM". Can you please help me for this?
Working with Date
Whilst I understand your logic of converting it to a string and then using string methods to convert it to your desired output, I believe a simpler approach is to use the Date object
function dateAdd(original, hours, minutes) {
const date = new Date(original);
date.setHours(original.getHours() + hours);
date.setMinutes(original.getMinutes() + minutes);
return date.toISOString();
}
When original = "2021-05-26T00:00:00.000Z" then the return value is "2021-05-26T10:20:00.000Z".
If you want a fixed time:
const date = new Date('2021-05-26T00:00:00.000Z');
date.setUTCHours(10);
date.setUTCMinutes(20);
date.setUTCSeconds(0);
date.setUTCMilliseconds(0);
// a cleaner approach:
date.setUTCHours(10, 20, 0); // hoursValue, minutesValue, secondsValue
console.log(date.toISOString());
Which produces the following:
"2021-05-26T10:20:00.000Z"
Another Solution
Your actual problem is being caused by the fact you call toString which returns a date string in the format of "Tue Aug 19 1975 23:15:30 GMT+0200 (CEST)" so when you're splitting by "T", that's way down at the end. toISOString will return the correct format.
Explanation
As you can see above, we avoid using string methods and use the methods that exist on Date. This approach is safer as you avoid issues with the difference between toISOString and toString. You may also find moment useful if you're using dynamic methods of changing dates regularly.
Note
In all honesty, I'm not entirely sure I understand the why behind what you're doing, so if I'm wrong please correct me so I can update my answer to be more relevant for you.
Learn More
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
I have the following data 2020-07-06T02:46:57.883+00:00. How do I convert it using moment js to 5 hours ago. for example. I used the following code but it doesnot work.
moment('2020-07-06T02:46:57.883+00:00.', "YYYYMMDD").fromNow();
but it is not working correctly
It seems like you are trying to achieve two outcomes through single command.
Ideally, if you want to first format the date and then use the fromNow() method, I would suggest the following way:
const date = moment('2020-07-06T02:46:57.883+00:00');
const formatedDate = date.format('YYYYMMDD');
const time = date.fromNow();
OR You can chain these operations
const time = moment('2020-07-06T02:46:57.883+00:00').fromNow();
Note: format() method returns a string, fromNow() cannot be chained to format method's response.
1) In response, a time stamp returned and is in T&Z format, ex: “2018-10-09T10:10:00Z”.
2) I have parsed the date and saved in a variable(date1) using “Regular Expression Extractor”.
3) In the successive request I would need to use the parsed time but this time I want to use it in millisecond format for the next request.
4) Here is my sample snippet looks like in “BSF PreProcessor”,
Here “date1” is a variable to which the value is parsed and extracted using Regular Expression Extractor.
Code snippet,
var time1 = vars.get(date1);
var timem1 = new Date(time1);
var timem1 = timem1.getTime();
vars.put("timem1",timem1);
But the above code didn’t help.
Can anyone please help me here?
Thanks in advance.
This is the format Instant can directly parse:
java.time.Instant.parse('2018-10-09T10:10:00Z').toEpochMilli()
// => 1539079800000
Please check the below;-
String b1 = "2018-10-09T10:10:00Z";
time=Date.parse("yyyy-MM-dd'T'HH:mm:ss'Z'", b1)
// get epoch milis
epoch_milis = time.getTime()
log.info("Current date in the specified format:>>>>>>>>>>>> " + epoch_milis);
Please check if this helps.
Also, it is recommended to use JSR223 instead of beanshell due to performance.
I am using 2.22.1 to format dates.
When i put in a date that comes from a date selector, moment will put the date back one day. For example, when I try to format a date in the following way:
Example 1:
const day = new Date(value).getDate();
const month = new Date(value).getMonth();
const fullYear = new Date(value).getFullYear();
console.log('day', day); // 7
console.log('month', month); // 5
console.log('fullYear', fullYear); //2018
Formatting function:
moment.utc(new Date(month + ' ' + day + ' ' + fullYear), 'MM-DD-YYYY').format('DD-MM-YY')
Output: 06-05-18
Expected: 07-05-18
Example 2:
Input: Thu May 31 2018 00:00:00 GMT+0100 (GMT Summer Time)
Formatting function:
moment.utc(new Date(value)).format('DD-MM-YY')
Output: 30-05-18
Expected: 31-05-18
moment.utc will convert the input to universal time.
You are running new Date(...) with an input that's based on GMT +1.
If you think about this, it makes total sense.
Your output is 30-05-18, because it's 11 PM / 23:00 o'clock on the previous day.
This (how ever) would in fact work:
moment('05-06-2018', 'MM-DD-YYYY').format('DD-MM-YY')
// alternatively (and preferrably) this:
moment.utc('05-06-2018', 'MM-DD-YYYY').format('DD-MM-YY')
and output: "06-05-18"
Because the non utc version does not take a time input in this example.
One of the reasons moment.js exists, is to get rid of Date in your code all together.
(Keep in mind tho, that Date has drastically improved now. DateTimeFormat is a game changer)
Please just read the momentjs documentation on how to properly use moment.
edit:
If you want to process 400000 dates with this, I'd advise using RegExp, .split, .exec, .slice or Date instead.
(I can relate since I wrote a client sided Log parser with javascript generators and Service Workers for a statistical anti-cheat analysis)
I truly recommend playing around with such things to raise your knowledge.
I just ran into this issue and a quick fix I found for the time being processed in "Zulu time" (due to the Z at the end of the string) is to add .LocaleString() after the date variable.
I find that for data consistency, it's easier to store data in UTC time and then convert it to the locale string when displaying the data to the user.
For example, I'm using:
moment.utc(dateVariable.toLocaleString()).format("MM/DD/YYYY")
I'm reading values from an old csv file that I have. This file has a lot of wrong data, it should has only time values, but sometimes it has date values on it.
I'm trying to valid time with moment.js, but when I run this code:
const moment = require('moment');
console.log(moment('19/07/9130','hh:mm').isValid());
It returns true, I'm doing something wrong??
1.
First of all, you are giving wrong format in moment function, you are passing data in DD/MM/YYYY format and defining format hh:mm. You should pass correct format.
2.
19/07/9130 is valid date which have year 9130 and it's absolutely valid future year. If you want to restrict maximum year, you can use isBefore method
var mydate = moment('19/07/9130', 'DD/MM/YYYY');
var isValid = mydate.isValid() && mydate.isBefore('2050-01-01');
Reading more the Moment.js docs, I find a third parameter that make Moment use strict parsing.
const moment = require('moment');
console.log(moment('19/07/9130','hh:mm',true).isValid());
This works fine!