How to Get the Current Time on a Button Click

How to get the current time on a button click?

In the second toast you need to reacquire the time, then add it to the toast, not the SimpleDateFormat. Here's the code:

Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm.ss aa");
String output = dateFormat.format(currentTime);
Toast.makeText(getApplicationContext(),"Time Is :" + output, Toast.LENGTH_LONG).show();

Display current time value after clicking start button

It is easier if you break them into two seperate functions like this:

var time;function ItsShowTime(){        var date = new Date();        var h = date.getHours();        var m = date.getMinutes();        var s = date.getSeconds();
h = (h < 10) ? "0" + h : h; m = (m < 10) ? "0" + m : m; s = (s < 10) ? "0" + s : s; time = h + ":" + m + ":" + s;
document.getElementById("Clock").textContent = time; setTimeout(ItsShowTime, 1000);}
function CurrentTime(){ document.getElementById("txt").innerText = time;}
ItsShowTime();
<!DOCTYPE html><html lang="en" dir="ltr">  <head>    <meta charset="utf-8">    <title>Digital Clock</title>  </head>  <body>    <input type="button" value="Start rit" onclick="CurrentTime()">    <div id="txt"></div>    <div id="Clock">

</div> </body></html>

When i press a button how to get time at that time and set to a text field

You just have to get the current Date and time from system and then display on your textview. Try this -

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
your_textView.setText(dateFormat.format(new Date());

get time and date in each button click android

Hi from the code it looks like you haven't updated your Date and Time in your onClickListener. The updated code should be like this :-

btnadd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// This will fetch your updated date and time
Date = simpleDateFormat.format(calendar.getTime());
Hrs = simpleHoursFormat.format(calendar.getTime());
Integer num1 = Integer.parseInt(edt1.getText().toString());
// Rest of your code

How to show Current Date Time when the button clicked in SQLlite Flutter?

Add DateTime to Employee model:

class Employee {
int id;
String name;
DateTime dateTime;

Employee(this.id, this.name, this.dateTime);

Map<String, dynamic> toMap() {
final Map<String, dynamic> map = new Map<String, dynamic>();
map['id'] = this.id;
map['name'] = this.name;
map['dateTime'] = dateTime != null ? this.dateTime.toIso8601String() : '';
return map;
}

Employee.fromMap(Map<String, dynamic> map) {
id = map['id'];
name = map['name'];
dateTime = map['dateTime'] != null? DateTime.parse(map['dateTime']): null;
}
}

DateTime.now() returns current DateTime of user.We will pass this whenever user is updating or adding new data.We will create another data column and cell for showing time.The datetime needs to be converted to presentable string so we will use our custom function getFormattedDate and lastly show it in Text widget.

Future<List<Employee>> employees;
TextEditingController controller = TextEditingController();
String name;
int curUserId;

final formKey = new GlobalKey<FormState>();
var dbHelper;
bool isUpdating;

@override
void initState() {
super.initState();
dbHelper = DBHelper();
isUpdating = false;
refreshList();
}

refreshList() {
setState(() {
employees = dbHelper.getEmployees();
});
}

clearName() {
controller.text = '';
}

validate() {
if (formKey.currentState.validate()) {
formKey.currentState.save();
if (isUpdating) {
Employee e = Employee(curUserId, name,DateTime.now());
dbHelper.update(e);
setState(() {
isUpdating = false;
});
} else {
Employee e = Employee(null, name,DateTime.now());
dbHelper.save(e);
}
clearName();
refreshList();
}
}

form() {
return Form(
key: formKey,
child: Padding(
padding: EdgeInsets.all(15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
verticalDirection: VerticalDirection.down,
children: <Widget>[
TextFormField(
controller: controller,
keyboardType: TextInputType.text,
decoration: InputDecoration(labelText: 'Name'),
validator: (val) => val.length == 0 ? 'Enter Name' : null,
onSaved: (val) => name = val,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
FlatButton(
onPressed: validate,
child: Text(isUpdating ? 'UPDATE' : 'ADD'),
),
FlatButton(
onPressed: () {
setState(() {
isUpdating = false;
});
clearName();
},
child: Text('CANCEL'),
)
],
),
],
),
),
);
}

SingleChildScrollView dataTable(List<Employee> employees) {
return SingleChildScrollView(
scrollDirection: Axis.vertical,
child: DataTable(
columns: [
DataColumn(
label: Text('NAME'),
),
DataColumn(
label: Text('DELETE'),
),
DataColumn(
label: Text('DATE'),
),
// DataColumn(label: Text("")'null')

],
rows: employees
.map(
(employee) => DataRow(cells: [
DataCell(
Text(employee.name),
onTap: () {
setState(() {
isUpdating = true;
curUserId = employee.id;
});
controller.text = employee.name;
},
),
DataCell(IconButton(
icon: Icon(Icons.delete),
onPressed: () {
dbHelper.delete(employee.id);
refreshList();
},
)),
DataCell(

Text(((DateTime date) =>
"${date.hour % 12}:${date.minute} ${date.hour > 12
? 'PM'
: 'AM'}")(
employee.dateTime) + ' ${getFormattedDate(employee.dateTime.toIso8601String())}'),
onTap: () {
//Any action
},
),
]),
)
.toList(),
),
);
}

list() {
return Expanded(
child: FutureBuilder(
future: employees,
builder: (context, snapshot) {
if (snapshot.hasData) {
return dataTable(snapshot.data);
}

if (null == snapshot.data || snapshot.data.length == 0) {
return Text("No Data Found");
}

return CircularProgressIndicator();
},
),
);
}

@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(

title: new Text('Stay_Safe'),
centerTitle: true
),
body: new Container(
child: new Column(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
verticalDirection: VerticalDirection.down,
children: <Widget>[
form(),
list(),
],
),
),
);
}


String getFormattedDate(String date) {
var d = DateTime.parse(date);
return [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
][d.month - 1] +
" " + d.day.toString() +
"," +
d.year.toString();
}

How to get Time After button is clicked with PHP

Try this :

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>    
<button onclick="Funct()">Get Time</button>

JS

    function Funct(){
var data = {};
$.ajax({ type: 'POST', url: 'php_file.php', data: data, dataType: 'json', encode: true })
.done(function (data) {
console.log(data.time);
}).fail(function (data) {
console.log(data.responseText);
});
}

PHP

    <?php 
$data['time'] = date('m/d/Y h:i:s a', time());
echo json_encode($data);

Get time a button is clicked, store it in the database then display on page in React

If you're trying to get the time the user checked in when they click on the check-in button, you can use the in-built javascript Date function to get the current date and time.

In the onCLick method from the frontend, you can grab the current time by declaring a new Date variable like:

var timeCheckedIn = new Date()

then you can send timeCheckedIn to the API

In your API, you can accept the time via the object or form data you're sending to the API like:

router.get('/', auth, async (req, res) => {
const { timeCheckedIn } = req.body
});

you can read more on using expressJS to handle the body of a request here

To display the date stored in the database, that will also depend on how you're retrieving the data from the server.

you can try the above to see if it helps



Related Topics



Leave a reply



Submit