how to get default timezone time in moment timezone - momentjs

I am using moment timezone to set default time
$moment.tz.setDefault('Europe/London');
$moment().toString();
is providing me the time in the defined timezone. but I need the timestamp. so I am using
$moment().now();
but it's returning the timestamp in local timezone. how can I get the timestamp of the default timezone(Europe/London)?

Moment.now is not really a public api. It is intended to be used for testing purposes only. All that you want to do is format a moment, so your code would be as follows:
moment.tz.setDefault('Europe/London');
moment().format(); //"2016-10-18T21:57:39+01:00"

Related

How can I get SignalR to stop changing my date/time values?

I have a simple class that contains a DateTime property. When I set the value of this property using DateTime.Now() the value is correct. However, when I pass this class object as a parameter via SignalR, on the receiving end SignalR has changed the DateTime so that it no longer matches the original DateTime. How can I get SignalR to stop manipulating my DateTime values? This issue seems to have started with a recent update to the latest SignalR nuget packages.
This seems to be a problem when the hub and the client are in two different time zones. It seems Microsoft is trying to help, by adjusting the date/time to the local time zone, but I want the original value, not the value Microsoft "thinks" I want.
When you want two systems to communicate with each other I would recommend using always the DateTime in UTC for various reasons. In your case you have two options here:
1 - Send the date as string string date = DateTime.Now.ToString(CultureInfo.InvariantCulture); so on the client side you just need to parse the datetime like DateTime.Parse(date, CultureInfo.InvariantCulture);.
2 - Send the date in UTC like DateTime.UtcNow; so event if the SignalR tries to change the date, it will have the DateTime.Kind as UTC. In this case or you will get the current date correctly, or you just adjust on the client side to the local time like receivedDate.ToLocalTime();
This one was a real head scratcher as I had the exact same issue. The client was storing the correct time but by the time it hit the Hub... it had changed. I'm really glad you posted this as I wouldn't have imagined this issue being possible. #Kiril1512 posted the correct resolution. In my case I used his second option as I didn't want to change my model... although simply converting to a string would have been simpler. While I did follow his suggestion and convert everything to DateTime.UtcNow()... I am thinking this was unnecessary as I noticed even previously stored dates converted correctly. This makes me think that either this isn't necessary to do, or dates are converted to Utc when they hit the Hub automatically which may be what the issue was to begin with?
Either way I posted this as I discovered that converting this date back to Local time was a little more involved. Here is how I ended up doing the conversion which resolved this issue for me that I gathered from this resource:
DateTime convertedDate = DateTime.SpecifyKind(
DateTime.Parse(msg.CreatedOn.ToString()),
DateTimeKind.Utc);
var kind = convertedDate.Kind;
DateTime dt = convertedDate.ToLocalTime();

Display a FrozenTime object in ISO_8601 while converted to a timezone

I have a Cake\I18n\FrozenTime object that I need displayed both as 2020-09-11T04:15:44+00:00 and converted to a specific timezone.
Normally, I'd call ->format('c'), but that uses the UTC according to my app configuration.
I know I can convert to a timezone using ->i18nFormat('yyyy-MM-dd HH:mm', 'Europe/Copenhagen'), but then I'll lose the convenience of the c date format shorthand. IntlDateFormatter predefined constants are lacking, and those from DateTimeInterface, (specifically, \DateTime::ATOM) don't work.
So before I go ahead and reinvent the wheel with ->i18nFormat("yyyy-MM-dd'T'HH:mm:ssxxx", 'Europe/Copenhagen'), is there a better way to display a Cake\I18n\FrozenTime in a specific date format and a specific timezone?
If you want to keep a date object, you can simply apply the timezone conversion on the object.
Frozen* objects are immutable, so you'll end up with a new object when applying the conversion:
echo $obj->setTimezone('Europe/Copenhagen')->format('c')
See also
Chronos API > \Cake\Chronos\ChronosInterface::setTimezone()

spring.jackson.date-format add extra 4 hours to given input

I want to format java.util.Date.I get year month and day correctly but when I insert data to database I get 4 more hour.For example if I insert 2017-12-18 12:00
then inserted row will be 2017-12-18 16:00
My controller:
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String insertRequest(#RequestBody EmployeeRequest employeeRequest) {
System.out.println(employeeRequest.getDate());
requestService.insertRequest(employeeRequest);
return "inserted and sent mail";
}
My model :
#NotNull
private Date date;
My application.properties
spring.jackson.date-format=yyyy-MM-dd HH:mm
Thanks in advance
This is not a date formatting error, this is very likely related to TimeZone. Depending on how your Database and Application Server are configured it appears that they are using different default timezone's.
Have you tried reading the data back OUT of the database into Java? If the database is properly storing the timezone then it should Just Work when you read it back into your java object. If not, i'd suggest first updating your Date/Time format to include the timezone e.g. spring.jackson.date-format=yyyy-MM-dd HH:mm:ssZ. Then the database should at least have access to the appropriate timezone.
If this doens't work, the proper mitigation really depends on your application and how it needs to make use of time / timezones. It could be that what you have is actually fine, it's just that when you manually inspect the database it's displaying to you the time in the default timezone. You could also just set your database and app servers to use the same timezone, but this can be a configuration nightmare.
Side note: as some general advice, I'd high recommend using either java.time.* or jodatime libraries instead of java.util.Date if at all possible. This isn't related to this specific issue, but they are much more robust date/time libraries than the legacy java.util.Date

MomentJS toISOString with local timezone

I've been using toISOString to serialize momentJS date before sending to the server via jQuery. It works fine for me except it converts date to UTC but I need to keep the local timezone. Does momentJS have a method for this?
You can either call .format() without any parameters, or you can call .toISOString(true). Both are in ISO 8601 extended format, the difference is only in whether milliseconds are included or not.
// get the current moment, in local mode
const m = moment();
// format without parameters will give the ISO string including offset
console.log(`moment().format() === "${ m.format() }"`);
// if you want to include milliseconds, you can use toISOString(true) instead
console.log(`moment().toISOString(true) === "${ m.toISOString(true) }"`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
Added in 2.20.0:
moment().toISOString(true)
Output:
"2018-05-13T16:16:13.507+03:00"
Found answer here.
Documentation.

Spring mvc: How can I set timezone per user?

I have data in database stored in UTC.
Every user has timezone in his setting. How can I handle timezone conversion during display and save?
Spring does not have built-in support for this like they do for locales. There is a ticket requesting this functionality but it has been been around since 2005.
If you are using JSP, you can use the fmt:timeZone tag to set the timezone to be used on any nested fmt:formatDate tags.
Wouldn't it help to have a converter / PropertyEditor for your Date objects that does exactly that (applies the user timezone when converting to String for displaying and the UTC timezone when converting back to a Date for processing) ?

Resources