I'm using react-datetime to render a calendar to user for date/time selection. How can I get the parse the value stored in state and turn it into a readable date so I can render that elsewhere in my UI.
I sent date in a post request and the value looks like: 2018-10-26T18:15:47.608Z. When I try to render that time in a table it gets stripped to this value 1540577747608. I want to display the zulu time for now.
this.state = {
date: new Date()
}
dateChange = date => this.setState({ date });
render() {
return (
<div>
<label>Choose a start date/time:</label>
<Datetime
onChange={this.dateChange}
value={this.state.date}
input={false}
isValidDate={validDate}
open={true}
utc={false}
onClickDay={value => alert("day" + value + "clicked")}
/>
</div>
</div>
In a different component where I want to render the date,
the value is being retrieved from an api call and being stored
formatDate: response.data.data.date
Then, I'm rendering in a table: <td key={schedule.formatDate}>{schedule.formatDate}</td>
Date does not have easy method for time formatting.
If you want to display the UTC time - or zulu time - you must use the dedicated methods to access hours, minutes and seconds and format them manually.
For example, the following displayes the UTC hours and minutes:
`${event.getUTCHours()}h${event.getUTCMinutes()}`
Related
i'm using react DateTime and i want to display or at least console the selected date and time so i could save it in a database later on
the input takes today's date and current hour as a initiale value and i can console it easily, but when i select an other day an exeption shows up.
there is a useState hook that i use to initialize the date variable
const [date,setDate] = useState(new Date() )
<Datetime
isValidDate={(current)=>{
let today= new Date()
return current.isAfter(today)
}}
dateFormat="DD-MM-YYYY"
onChange={()=>setDate((e)=>e.target.value)}
value={date}>
</Datetime>
According to https://www.npmjs.com/package/react-datetime, your onChange should be:
onChange={(val) => setDate(val)}. You get a moment date as input for onChange.
Furthermore, you get an exception because your current onChange is totally invalid:
It doesn't receive an event but the actual selected moment value.
Even it it was getting an event, the e should be coming from the onChange and not from the state setter:
onChange={(e) => setDate(e.target.value)}.
I'm trying to get the hour in different ways from a datetime-local input but every time I've got the output as "invalid" date.
So I would like to know how can I get the hour from a datetime-local input using jquery or js.
Here is what I've tried:
var fine = moment($('#datafine').val).format("HH");
And without moment that was something like
var datafine = new Date($('#datafine').val);
When you get the value from the input, it is converted to a standard format, regardless of the displayed format:
One thing to note is that the displayed date and time formats differ from the actual value; the displayed date and time are formatted according to the user's locale as reported by their operating system, whereas the date/time value is always formatted yyyy-MM-ddThh:mm.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local
So you can use this with new Date(val).getHours() to get the hours.
Using jQuery:
var hour = new Date($('input[type="datetime-local"]').val()).getHours()
console.log($('input[type="datetime-local"]').val(), hour)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="party">Enter a date and time for your party booking:</label>
<input id="party" type="datetime-local" name="partydate" value="2019-06-01T19:30">
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours
If I understand correctly what you're trying to do, something like this may help. You would just need to add in the date value from your input into new Date(). The code below would give you the hours in the specified locale.
const date = new Date();
const options = { hour12: false, hour: 'numeric'};
const hours = date.toLocaleTimeString('en-US', options);
console.log(hours)
Date.prototype.toLocaleTimeString() on MDN
How do I determine if an entry in my database (laravel) was stored during Daylight Savings time using the created_at field?
I'm trying to calculate the time difference between when a record was saved and now so I can do can show something like 3 hours ago or 49 minutes ago. This was working fine, until the UK entered Daylight Savings Time a couple of weeks ago and now all times are inflated by 1 Hour.
I'm using moment to show the result like the following;
getElapsedString(from) {
return moment(from).fromNow();
}
The data is stored in my database in the following format and this is what is passed in to the above function as from;
2019-04-10 09:27:48
I'm not doing anything to the dates when they are stored. This is handled by Laravel.
Inside config/app.php there is a
'timezone' => ''
you can set it to:
'timezone' => 'America/New_York'
It will set the default timezone and save created_at with this timezone with current daylight
I have one object called appointment which has two properties: StartDate and EndDate.
When I make POST request I send these values using ISOString time .
this.appointment.StartDate.toISOString()
On the server-side, I received these properties with correct values. Also, it seems to be correct when I create model in order to save appointment to the database. I used .ToUniversalTime() method.
var newAppointment = new Appointment()
{
StartDate =Convert.ToDateTime(model.StartDate).ToUniversalTime(),
EndDate = Convert.ToDateTime(model.EndDate).ToUniversalTime(),
SpecialityId = speciality.Id,
LocationId = location.Id,
PatientId = patient.Id,
UserId = user.Id,
Observations = model.Observations
};
But in database I found another values. Can explain somebody why is this behaviour ?
For instance, I used 2017.09.01 11:00 for StartDate and in database i found 2017-09-01 08:00
The server and database is located in the westeurope.
A few things:
Don't call ToUniversalTime in a web application. It's designed to convert from the server's local time zone to UTC. The server's time zone should be irrelavent to your application. Web applications should never use ToUniversalTime, ToLocalTime, DateTime.Now, TimeZoneInfo.Local, DateTimeKind.Local or any other method that uses the time zone of the computer it's running on.
Ideally, on the server side, your model.StartDate and model.EndDate would already be DateTime objects, because they'd have been deserialized that way. Therefore, you probably don't need to call Convert.ToDateTime. If they are strings, then I would adjust your model class accordingly.
On the client side, assuming StartDate and EndDate are JavaScript Date objects, and they were created using local time values (that is, the time zone of the browser), when you call toISOString, you're not just getting a string in ISO 8601 format - it is also converting it from the browser's time zone to UTC.
In your example, the UTC time is 3 hours ahead of UTC for the date and time shown. From your profile, I see you are located in Romania, which is indeed UTC+3 for this date, because it is currently observing Eastern European Summer Time. When Summer Time ends (on October 29, 2017 at 04:00), it will return to UTC+2. For this reason, you cannot simply add three hours to all values.
If you want to send local time values from the client, you should send them in ISO 8601 format, without any Z or offset, for example 2017-09-01T11:00. There are several ways to achieve this:
The best way is to not have them in a Date object to begin with. For example, if your input uses the <input type="datetime-local" /> input type (as specified in HTML5), the .value property is not a Date object, but rather a string in ISO 8601 format.
If you can't avoid a Date object, then create a local ISO string, like this:
function dateToLocalISOString(date) {
var offset = date.getTimezoneOffset();
var shifted = new Date(date - offset * 60 * 1000);
return shifted.toISOString().slice(0, -1);
}
OR, using Moment.js:
moment(yourDateObject).format("YYYY-MM-DD[T]HH:mm:ss.SSS")
Lastly, you will probably read advice from others about storing these as UTC. Don't listen. The advice "always use UTC" is shortsighted. Many scenarios require local time. Scheduling appointments is a primary use case for local time. However, if you need to act on that appointment, you'll use the current UTC time, and you'll also need some information about the time zone for the appointment so you can convert from UTC to the appointment's time zone. For example, if this is something like an in-person doctor's office appointment, then it's safe to assume the time zone of the doctor's office. But if it's an appointment for an online meeting, then you'll have to capture the user's time zone separately and apply it on the back end where appropriate.
The problem is with your current timezone.
What your application does is get current timezone (+3) in this case.
Now it got your timezone but it will convert to utc time. So what will happen, your current time will be -3 hours.
If you not adjust to summer and winter time then you can simply add 3 hours to the datetime. Otherwise you have to get the offset of your timezone and add that to the current datetime value.
Take care if you use this application in different timezones. For example You life in +3 and some else life in +2 timezone.
I have a column in table called registerdate with type datatime in mysql.
Say right now time is "2015-10-10 06:00:00" local time.
In database I am storing UTC time, so it will be converted to "2015-10-10 00:30:00" as local time is +530 GMT. So correct time is stored in database.
How can I convert registration time to local time when I retrieve it.
This is how I converted before saving datetime to db
moment.utc(new Date()).format("YYYY-MM-DD HH:mm:ss")
This is what i am trying to convert it back to local time.
moment.utc(registerdate, "YYYY-MM-DD HH:mm:ss").local().format("HH:mm:ss")
This makes no change to saved date and render the same as stored in db.
Second Approach: It further subtract 5:30 hours instead of adding to it.
moment.utc(_obj[i].StartTime).format("HH:mm:ss")
Which step I am doing wrong.
I don't think using JavaScript it's a good idea for saving a datetime in MySQL. I think is better to use the MySQL function UTC_TIMESTAMP(). For example:
INSERT INTO `ITEMS` (`name`, `date_add`) VALUES ('item name', UTC_TIMESTAMP());
Now, when you retrieve the UTC datetime from MySQL, you can convert it to a Moment object like this:
var utc = moment.utc(MYSQL_DATETIME, 'YYYY-MM-DD HH:mm:ss');
var local = utc.local();
// var local = moment.utc(MYSQL_DATETIME, 'YYYY-MM-DD HH:mm:ss').local();
console.log( local.format("HH:mm:ss") ); // 15:54:31
console.log( local.fromNow() ); // a minute ago
I don't see anything wrong in your code. Maybe it's something in the application side (PHP?).
Another thing. Using the method utc() without parameters is the same as calling utc(new Date()). So you can simply use this in your convertion to MySQL datetime:
//moment.utc(new Date()).format("YYYY-MM-DD HH:mm:ss")
moment.utc().format("YYYY-MM-DD HH:mm:ss")
Note: excuse my bad English.
You probably don't need to use moment at all. If the date coming from the database is a valid date all you need to do is
var someDate = new Date("2015-10-10 00:30:00");
$("#content").html(someDate.toString());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
<div>
You will see that this gives you the local time as JS assumes that you gave it local time.
you can add "Z" to the end of the string to force JS to assume the input value as UTC time. When "Z" (Zulu) is tacked on the end of a time, it indicates that that time is UTC http://www.wikiwand.com/en/ISO_8601#/Time_zone_designators
var someDate = new Date("2015-10-10 00:30:00Z");
$("#content").html(someDate.toString());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
<div>
In case you need to use moment
instead of new Date("2015-10-10 00:30:00Z")
you could do moment("2015-10-10 00:30:00Z")
Hope this helps