angularjs - confusion with date formats - angularjs

I am super confused with date formats and need some clarifications. I am trying to pre-populate a form with a date and have set $scope.selectedDate = c.data.Appt.enrolled.start_date;
In my console, c.data.Appt.enrolled.start_date is a string:
However, when I set $scope.selectedDate to that, nothing shows up.
Conversely, if I add new Date in front
(new Date(c.data.Appt.enrolled.start_date))
a date shows up, but it is one day before (April 24, 2018).
In addition to that, when I try to insert the "new Date" version into a function (even though it isn't the correct date), I get a warning in the console saying "Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release."
Can someone explain how I should format the dates so I: 1) get the correct date and not one day prior and 2) am able to plug it into a function without getting that warning?
Thanks!

Since the date is a string with no time zone information (just the date) JavaScript Date parser will treat it as universal(UTC, which is in Greenwich Mean Time) time at 00:00 hours. Then it will subtract the offset of your locale's timezone in hours, and will result in the date being a few hours before or after the day you actually want. This is a common point of confusion.
The best way to solve this is to parse the date manually:
function localDate(dateString) {
var d = dateString.split(/\D/);
return new Date(d[0], d[1]-1, d[2]);
}
See this question for more information: Javascript: parse a string to Date as LOCAL time zone
Moment.js gives that warning because it's considered bad practice to rely on the string parsing that new Date() does since it will have different results in different browsers (IE\Firefox\Etc.). It's more cross-browser friendly to build the date using this form: new Date(year, month, day). (Note that the month starts at zero, not 1)

Related

timezone conversion using date-fns

I’m trying to work with date-fns-tz in my react-based webpage and couldn’t make the following use-case to work.
I have a date input in a form that should be submitted to the backend that stores the data in local timezone.
A user in GMT+2 timezone selects 14:00 on 1/Feb/2021 in the UI, which correlates to 1612180800 timestamp (as the UI was opened in GMT+2), but it should eventually get sent to the backend as 14:00 in GMT-8, which is actually 1612216800 timestamp.
What’s the right way to get this conversion (from 1612180800 --> 1612216800 ) to work?
I tried to work with various date-fns functions, but hadn’t found the right one.
You'll need two things to make this work correctly:
An IANA time zone identifier for the intended target time zone, such as 'America/Los_Angeles', rather than just an offset from UTC.
See "Time Zone != Offset" in the timezone tag wiki.
A library that supports providing input in a specific time zone.
Since you asked about date-fns, you should consider using the date-fns-tz add-on library.
Alternatively you could use Luxon for this.
In the past I might have recommended Moment with Moment-TimeZone, but you should review Moment's project status page before choosing this option.
Sticking with date-fns and date-fns-tz, the use case you gave is the very one described in the docs for the zonedTimeToUtc function, which I'll copy here:
Say a user is asked to input the date/time and time zone of an event. A date/time picker will typically return a Date instance with the chosen date, in the user's local time zone, and a select input might provide the actual IANA time zone name.
In order to work with this info effectively it is necessary to find the equivalent UTC time:
import { zonedTimeToUtc } from 'date-fns-tz'
const date = getDatePickerValue() // e.g. 2014-06-25 10:00:00 (picked in any time zone)
const timeZone = getTimeZoneValue() // e.g. America/Los_Angeles
const utcDate = zonedTimeToUtc(date, timeZone) // In June 10am in Los Angeles is 5pm UTC
postToServer(utcDate.toISOString(), timeZone) // post 2014-06-25T17:00:00.000Z, America/Los_Angeles
In your case, the only change is that at the very end instead of calling utcDate.toISOString() you'll call utcDate.getTime().
Note that you'll still want to divide by 1000 if you intend to pass timestamps in seconds rather than the milliseconds precision offered by the Date object.
You can use 'moment' to convert timezone.
1.Create a moment with your date time, specifying that this is expressed as utc, with moment.utc()
2.convert it to your timezone with moment.tz()
For example
moment.utc(t, 'YYYY-MM-DD HH:mm:ss')
.tz("America/Chicago")
.format('l');

How to post date combined with hours with React JS?

When I try to make a post request with React js to a make a reservation the time diminishes by two hours, while in the state it is exactly the time I wanted, meanwhile in the DB it is saved with two hours less. Example I try to save 11 o'clock instead saves 9 o'clock.
This is how format the date and time before passing it to the api call
const booking_date = new Date(year, month, day, hour, minute);
You can use a timestamp to get a more accurate consistent date
const booking_date = new Date(year, month, day, hour, minute).getTime();
Then if you need an actual date string you can convert it back to a date using new Date(). This is likely a timezone issue so a timestamp would mitigate that, along with giving you the extra bonus of being able to send less data in the api call.
Alternatively, if you NEED a string date you can use:
new Date().toUTCString()
which will convert the date to a UTC string that is consistent across the world (it will give you the same value no matter your location) since it uses the standardised UTC timezone.
See more here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
You can use moment.js. If you have a date string then convert it using moment.js before sending the post request or if you do not have any date string, you just need to pick the current date and time means then you can use as like below with the desired format you need. I'd recommend to always use UTC internally, and convert to a timezone only when displaying the date to the user
import moment from "moment";
let date = moment().format('MM-DD-YYYY hh:mm:ss')} // It will return 06-16-2020 08:54:00

Alexa AMAZON.DATE slot default to past dates

I am using the AMAZON.DATE slot and I would like it to default to past dates.
For example, if a user says Monday I would like it to automatically select last Monday rather than next Monday.
In the documentation it confirms that it defaults to 'on or after the current date':
"Utterances that map to a specific date (such as "today", "now", or
"november twenty-fifth") convert to a complete date: 2015-11-25. Note
that this defaults to dates on or after the current date (see below
for more examples)."
For my application there is no way a future date would make sense so it wouldn't be too difficult to manually program this in but I just wondered if there was any other way of doing it?
No, you cannot change the behavior of built in slots, so if Alexa resolves user's answer as a date - before passing it to your further processing just subtract 7 from resolved value. It will give you the date in the past.

Timezone issues when sending Calender entries using Java mail API

We are using JavaMail API to send calendar entries. But the recipients of Outlook have time zone issues, as meetings show wrong timings. In general our approach is as follows:
First of all we have,
SimpleDateFormat iCalendarDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
we then use iCalendarDateFormat.setTimeZone(TimeZone.getTimeZone(receiverTimeZone));
Finally, we use Calendar.getInstance() for start and end to manipulate Calendar fields,
and hence we have Date startDate = startTime.getTime();
Date endDate = endTime.getTime();
When we are about to send request as per icalendar specification we have ,
"DTSTAMP:" + iCalendarDateFormat.format(startDate) + "\n" +
"DTSTART:" + iCalendarDateFormat.format(startDate)+ "\n" "DTEND:" + iCalendarDateFormat.format(endDate)+ "\n"
Is this the correct approach?. Please comment.
Thanks
tl;dr
iCalendar format tracks the date-time separately from its intended time zone. You must juggle both parts appropriately.
Always use java.time classes. Never use legacy classes like Calendar & SimpleDateFormat.
Details
Caveat: I have not used iCalendar data before. So I may be incorrect in my understanding.
Looking at pages 31-33 of the RFC 5545 spec, it seems the authors of that spec assume you always want the date-time to be recorded separately from the time zone.
A moment, a point on the timeline, needs the context of a time zone or offset-from-UTC. For example, "noon on the 23rd of January next year, 2021" is not a moment. We do not know if you mean noon in Tokyo Japan, noon in Toulouse France, or noon in Toledo Ohio US — all very different moments, several hours apart.
To provide the context of an offset, a date and time must be accompanied by a number of hours-minutes-seconds such as 08:00. For an offset of zero hours-minutes-seconds, use +00:00.
2021-01-23T12:00:00+00:00
As an abbreviation of an offset of zero, +00:00, the letter Z can be used, pronounced “Zulu”. For example:
2021-01-23T12:00:00Z
But, strangely, the iCalendar spec wants to track the date and the time-of-day separate from the time zone. So this:
2021-01-23T12:00:00
…and a time zone field elsewhere:
America/New_York
And the iCalendar spec opts for the harder-to-read “basic” variation allowed by ISO 8601, which minimizes the use of delimiters. So this:
20210123T120000
For such a string, we must parse as a LocalDateTime. This class represents a date with a time-of-day but lacking any time zone or offset-from-UTC.
DateTimeFormatter f = dateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmss" ) ;
String input = "20210123T120000" ; // “Basic” variation of ISO 8601 format.
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
To determine a moment, we must apply a time zone. I assume iCalendar uses proper time zone names (Continent/Region format) and not the 2-4 letter pseudo-zones such as PST, CST, IST, and so on.
String zoneName = receiverTimeZone ; // Variable name taken from your code example, though you neglected to show its origins.
ZoneId z = ZoneId.of( zoneName ) ;
Apply the zone to get a ZonedDateTime, a moment, a point on the timeline.
ZonedDateTime zdt = ldt.atZone( z ) ;
Going the other direction, let's start with the current moment.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;
And generate string values for iCalendar.
DateTimeFormatter f = dateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmss" ) ;
String iCal_DateTime = now.format( f ) ;
String iCal_ZoneName = now.getZone().toString() ;
Never use the terrible legacy date-time classes bundled with the earliest versions of Java: Calendar, GregorianCalendar, java.util.Date, SimpleDateFormat, and so on. These were supplanted years ago by the modern java.time classes defined in JSR 310.
Hard to tell without seeing the actual content of your iCalendar file, along with the expected start and end datetime with timezone information but you seem to be generating the DTSTART in floating time (datetime with local time). Although your code sample seems to imply that you have access to the recipient's timezone (receiverTimezone), this is a very fragile approach.
Instead, you should use either the datetime with UTC time or the datetime with local time and timezone (where the timezone does not have to be the receiver timezone).
If the event is not recurring, the most simple approach is to use datetime with UTC time.
See https://www.rfc-editor.org/rfc/rfc5545#section-3.3.5 for the definition of each format.
I had same problem, for which I struggle lot. So below are my findings:
Outlook works smoothly with UTC Timezone. If we set date & time with UTC Timezone then outlook automatically converts this UTC Time into user corresponding Timezone. We will have to use 'Instant' object for DTSTART:, DTEND: and for DTSTAMP(Optional but recommended) also.
Quick Test just use "DTSTART:"+Instant.now() in ical String.
And in Java 8 for getting UTC Time java time API provides Instant.now() through which you can get your system time in UTC format. Java 8 also provides method like
a. Instant.ofEpochMilli() - This returns Instant which can directly use in ical Sting.
b. new Date().toInstant() Which returns UTC Instant object.
There are few scenarios where input date and time sources are different:
If you are fetching Date and Time from database then in this case database is not storing Timezone its only saving Date & Time. So first convert the Date & Time in that Timezone in which it was saved in database, in my case I was storing Date & Time after converting in 'EST' Timezone and Date value was of EST but time zone was not there in DB. So while fetching Date & Time value from DB I have appended Timezone in the Date value and then further converted to EPOC time using below method
public static long getEpocTimeWithTimezone(Date date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateTimeFormatter dateTimePattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(simpleDateFormat.format(date), dateTimePattern);
long epochInMilliSeconds = dateTime.atZone(ZoneId.of("America/New_York")).toEpochSecond() * 1000;
return epochInMilliSeconds;
}
Then Just Use as below code for ical String:
Instant startDt = Instant.ofEpochMilli(getEpocTimeWithTimezone(//pass your date here
)).truncatedTo(ChronoUnit.MINUTES);
Now set this Instant object(startDt) directly to "DTSTART:":
"DTSTART:"+startDt+"....then in same fashion "DTEND:" also.
In second scenario you have Date with Timezone (make sure after conversion you did not loses your actual Timezone, Like in 1st scenario after saving Date in DB we actually lost Timezone but it was showing Timezone IST that was dummy so be careful about this)
So in this case just assume myDateObject is Date object. So just get the Instant (which
will be in UTC) object from myDateObject by using toInstant() of Date class.
Instant startDt = myDateObject.toInstant().truncatedTo(ChronoUnit.MINUTES);
I am using .truncatedTo(ChronoUnit.MINUTES); because if we will not use this then
we might get some extra min or second in Meeting invite Time section.
So the final String for outlook mail should be some like:
.
.
.
"BEGIN:VEVENT\n"+
"DTSTART:"+startDt+"\n"+
"DTEND:"+endDt+"\n"+
.
.
.
VVI Note: Since Z is representation of UTC time zone, So just adding Z in the last of Time will not be UTC zoned Time, You will have to convert the Date & Time then only accurate time will come on Outlook. For verifying your Time is in UTC format or not just save the .ics attached file (which you got in Email) in local and check Date & Time are coming as DTSTART:2020-05-15T13:57:00Z or not If not then you are not converting the Date correctly in UTC.

Stata: Convert String to Date

I am relatively new to Stata. I have a string variable time that records year and month in the following format:
2000m1
2000m2
2000m3
...
2015m12
I would first like to create a date variable that looks identical (but it has to be in the date format) to the above. Second, I would like to separate year and month components into two different variables, and third, I would like to rename the month component to January, February, etc.
For the first task, the command date = date(time, "YM") returns an empty variable and I can't figure what I am doing wrong.
The function date() yields daily dates, not monthly dates or any other kind of date that isn't a daily date. See its help (help date()) which begins
date(s1,s2[,Y])
Description: the e_d date (days since 01jan1960) corresponding to s1
based on s2 and Y
s1 contains the date, recorded as a string, in virtually
any format. Months can be spelled out, abbreviated (to
three characters), or indicated as numbers; years can
include or exclude the century; blanks and punctuation are
allowed.
s2 is any permutation of M, D, and [##]Y, with their order
defining the order that month, day, and year occur in s1.
##, if specified, indicates the default century for
two-digit years in s1. For instance, s2="MD19Y" would
translate s1="11/15/91" as 15nov1991.
In essence, it needs to be told a day, month and year. You supplied a month and year, and date() won't (can't) play.
As documented at the same place, daily() is a synonym for the same function and it's good practice to use it to remind yourself (and readers of your code) of what it does.
Correspondingly, monthly() provides an easier solution to create a monthly date from string input than in your own answer. Try out solutions using display (di is allowed) on simple cases where you know the right answer.
. di monthly("2000m1", "YM")
480
. di %tm monthly("2000m1", "YM")
2000m1
Reading the documentation is crucial here. See help datetime for a start. There is a lot to explain as dates come in many different forms, but it's all documented.
See also help datetime_display_formats for how to display dates differently. (No "renaming" is involved here.) For example,
. di %tmMonth_CCYY monthly("2000m1", "YM")
January 2000
I figured out the first part. I post the answer to here for anybody who needs a reference:
gen date = ym(real(substr(time, 1,4)),real(substr(time,6,2)))
format date %tm
Try this code may be it works for you
string Date1 = String.Format("{0}", Request.Form["date"]);
string Date2 = String.Format("{0}", Request.Form["date1"]);
Date1 = DateTime.Parse(Date1).ToString("yyyy-MM-dd");
Date2 = DateTime.Parse(Date2).ToString("yyyy-MM-dd");

Resources